よく使い方を調べるので、今後のためにまとめてみようというメモ。
loopしたい対象:list
, dict
listA = [1, 2, 3, 4, 5]
dictA = {'a1': 1, 'a2':2, 'a3':3, 'a4': 4, 'a5': 5}
普通 for...in...
list
for item in listA:
print(item)
# output:
# 1
# 2
# 3
# 4
# 5
list
の場合、値をそのまま出力できる。
dict
for item in dictA:
print(item)
# output:
# a1
# a2
# a3
# a4
# a5
dict
の場合、keyの部分だけを出力される。
1, 2, 3, 4, 5数字を出力したいなら、values()
関数を使う。
for item in dictA.values():
print(item)
# output:
# 1
# 2
# 3
# 4
# 5
indexも欲しい
値だけではなく、何個目の要素を指定するindexも欲しい場合もよくある。その場合、いくつの方法がある。その中に一番便利な方法を紹介する。
list: enumerate()
enumerate()
関数を使う。
for index, value in enumerate(listA):
print(f"{index}: {value}")
# output
# 0: 1
# 1: 2
# 2: 3
# 3: 4
# 4: 5
list: range()
range()
関数を使う。
for index in range(len(listA)):
value = listA[index]
print(f"{index}: {value}")
# output
# 0: 1
# 1: 2
# 2: 3
# 3: 4
# 4: 5
range
関数は良いところは、関数の引数にstart, stop, step組み合わせて、作成するindexリストの調整には少し自由度があること。
例えば、index=1,3をLoop処理しない場合、range(start, stop, step)
で簡単に実現できる。list(range(0, len(listA), 2))
で[0, 2, 4]
リストを作れるので、これを利用すればと思う。
for index in range(0, len(listA), 2):
value = listA[index]
print(f"{index}: {value}")
# output
# 0: 1
# 2: 3
# 4: 5
dict
items()
関数を使う。
for index, value in dictA.items():
print(f"{index}: {value}")
# output
# a1: 1
# a2: 2
# a3: 3
# a4: 4
# a5: 5
二つリストを同時にLoopする
一つのリストをindex取れるLoopで行う時に、そのindexで別のリストの要素を取って処理をやれば行けると思う。もし、zip
関数を使えれば楽になる。
listA = [1, 2, 3, 4, 5]
listB = ['A', 'B', 'C', 'D', 'E']
for itemA, itemB in zip(listA, listB):
print(f"listA:{itemA}, listB:{itemB}")
# output
# listA:1, listB:A
# listA:2, listB:B
# listA:3, listB:C
# listA:4, listB:D
# listA:5, listB:E
zip
関数は、二つ以上のリストを同時Loopも可能。
zip
関数は、要素数が異なるリストを同時Loopも可能。(Loopの回数は短いリストの要素数になると思う。)
map関数
例えば、listAの要素を全て2倍になるリストが欲しい場合、map
関数利用するとすぐにできる。
listAx2 = list(map(lambda x: x * 2, listA))
リスト内包表記
先ほど、map関数の例は、リスト内包表記でもできる。
listAx2 = [ x*2 for x in listA]