科学の箱

科学・IT・登山の話題

Python

タプルの操作

投稿日:

タプルはPythonで提供されているデータ構造の一つ。タプルは固定長で変更できない複数の値の集合である。

タプルオブジェクト (tuple object) — Python 3.8.0 ドキュメント

タプルの生成は、変数にカンマで区切った値を代入する。

tup = 1,3,5
print(tup)
print(type(tup))

# (1, 3, 5)
# <class 'tuple'>

 

タプル内部にタプルを含むことも可能である。

tup = ((1,3,5), (2,4,6))
print(tup)

# ((1, 3, 5), (2, 4, 6))

 

様々なデータをタプルに変換することが可能である。

生成したリストをタプルに変換してみる。

l = [10, 11, 12]
print(l)
print(type(l))

# [10, 11, 12]
# <class 'list'>

tup = tuple(l)
print(tup)
#(10, 11, 12)

 

文字列をタプルに変換してみる

tup = tuple('string')
print(tup)

# ('s', 't', 'r', 'i', 'n', 'g')

 

タプルの要素を取得するためには[]で要素番号を指定する。

tup = tuple('string')
print(tup[4])

# n

 

タプルでは足し算が利用できる。

tup = 1,3,5
tup = tup + ('abc', 'xyz') + (2,4,6)
print(tup)

# (1, 3, 5, 'abc', 'xyz', 2, 4, 6)

 

タプルでは掛け算も利用できる。

tup = 1,3,5
tup = tup * 5
print(tup)
# (1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5)

 

タプルから値を取り出す操作をアンパックと呼ぶ。アンパックをするためには左辺にタプルの各要素を代入するための変数、右辺にアンパックしたいタプルを記述する。

tup = 1,3,5
a, b, c = tup
for i in a,b,c:
    print(i)

#
1
3
5

 

ただし、左辺の変数の数はタプルの要素数と一致する必要があるので少々取り扱いが面倒くさい。

tup = 1,3,5
a, b = tup
for i in a,b,c:
    print(i)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-d3bfa8403c9f> in <module>
      1 tup = 1,3,5
----> 2 a, b = tup
      3 for i in a,b,c:
      4     print(i)

ValueError: too many values to unpack (expected 2)

 

タプルの長さがわからないときにはイテレーションですべての要素を順番に取得できる。

tup = 1,3,5,7
for a in tup:
    print(a)
# 
1
3
5
7

 

先頭の一部のタプルだけ利用したいときにはアンパックで*restを利用する。ただしrestはlist型であることに注意する

tup = 1,3,5,7,9 
a, b, *rest = tup
print(rest)
type(rest)

# [5, 7, 9]
# list

 

メタ情報

inarticle



メタ情報

inarticle



-Python

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

kaggle Titanic Tutorial – 3

DecitionTreeのパラメータを調整する。 まずはMaxDepthから from sklearn.model_selection import LeaveOneOut from sklearn. …

no image

kaggle Titanic Tutorial – 1

KaggleでTitanic tutorialにチャレンジしてみる。 Titanic: Machine Learning from Disaster https://www.kaggle.com/c/ …

no image

SIGNATE お弁当の需要予測-4

今回はSeabornのpairplotを利用して相関の概要を見てみる。ただし相関を見るためにはデータのクレンジングが必要。 まずはnullデータのヒートマップを確認してみる。 sns.heatmap( …

no image

OpenCV

WindowsにOpenCVをインストールする場合に2つのやり方がある。 一つは様々な言語からOpenCVを利用できるようにする方法、2つ目の方法ではPythonからOpenCVを利用する方法である。 …

no image

Numpyまとめ

環境及びインポート numpyのインポートおよび環境確認 配列生成 配列をリストから生成 配列の属性を確認 すべての要素が同じ値を持つ配列を生成 空の配列を生成 numpy.linspace()を使っ …

2019年11月
« 10月   12月 »
 123
45678910
11121314151617
18192021222324
252627282930  

side bar top



アーカイブ

カテゴリー