Python Functions, Files, and Dictionaries4: Tupleって結局なんだっけ。

とりあえずprintでtuple使いましょう。

 

tupleにするは、英語でpack into tuple

13.1.1. Learning Objectives

At the end of this chapter, you will be able to:

  • Recognize when code is using implicit tuple packing
  • Use implicit tuple packing to return multiple values from a function
  • Read and write code that unpacks a tuple into multiple variables
  • Learn a common pattern that unpacks the results of calling enumerate on a sequence

 

Tupleの使い方

tupleはdictionary.items()で取得できる。

p[0], p[1]でunpackしている。らしい。

(a, b)というtupleをバラしてaとbでそれぞれ使うことをunpackという。

more readableにするには

でもpython interpretorは次のように書いたら自動的にunpackしてくれるという。

こんな感じです。

tupleはfunctionのoutputが2つ以上の時使う

list内のtupleをforで呼び出すと、tupleが要素としてでてくるのか・・・・

variable を swapするときにも使える。

Tupleの探し方

()parenthisがなくてもtuple

listの中にtupleがあることもある。

 

tupleはimmutableだけど探し方はlistと同じっぽい

 

lst = [(“a1”, “b1”, “c1”),(“a2”, “b2”, “c2”),(“a3”, “b3”, “c3”),(“a4”, “b4”, “c4”)]

print(len(lst))
print(lst[0])
print(len(lst[0]))
print(lst[0][2])

 

lst_tups = [(‘Articuno’, ‘Moltres’, ‘Zaptos’), (‘Beedrill’, ‘Metapod’, ‘Charizard’, ‘Venasaur’, ‘Squirtle’), (‘Oddish’, ‘Poliwag’, ‘Diglett’, ‘Bellsprout’), (‘Ponyta’, “Farfetch’d”, “Tauros”, ‘Dragonite’), (‘Hoothoot’, ‘Chikorita’, ‘Lanturn’, ‘Flaaffy’, ‘Unown’, ‘Teddiursa’, ‘Phanpy’), (‘Loudred’, ‘Volbeat’, ‘Wailord’, ‘Seviper’, ‘Sealeo’)]
print(lst_tups[0][2])

t_check = []
for t in range(len(lst_tups)):
t_check += [lst_tups[t][2]] #listにしないとlistに追加できないんだわ。
print(t_check)

list内のtupleはidを指定して取得できるよ!

for statement内でもtuple使えるよ!

for statement内でtupleのelementを指定できる件

print(“for statement内でtupleのelementを指定できる件”)
tups = [(3, 1), (4, 2), (5, 3)]
L = []
for x1, x2 in tups:
L.append(x1+x2)
print(L)

tups = [(3, 1), (4, 2), (5, 3), 1] #全部tupleでないと無理。
L = []
for x1, x2 in tups:
L.append(x1+x2)
print(L)

list内のtupleからdictionaryを作る。

x = dict(name = “John”, age = 45, country = “Norway”)
print(x)

#dictionaryから.items()でtupleとしてk-vを取り出す。
print(x.items())

#list内のtupleから辞書を作る。
tups = [(‘name’, ‘John’), (‘age’, 45), (‘country’, ‘Norway’)]
d = {}
for t in tups:
d[t[0]] = t[1]
print(d)

 

 

その他

unpacking tuple するなら*使おう(これはtupleだからunpackしてね!)という印

 

tuple?じゃない?けどoptional parameter

100を8進法で表示する。

 

これ意味不でした。

コメント