PythonでLoopをしたいときに、何のやり方を使っていますか?
今回はlist、dictの中身を一つずつ処理たい時によくある使い方を調べました。
まずは今回のloopしたい対象の中身はこのような感じになります。
listA = [1, 2, 3, 4, 5]
dictA = {'a1': 1, 'a2':2, 'a3':3, 'a4': 4, 'a5': 5}
for item in listA:
print(item)
# output:
# 1
# 2
# 3
# 4
# 5
list
の場合、値をそのまま出力できる。
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も欲しい場合もよくある。
その場合、いくつの方法がある。その中に一番便利な方法を紹介する。
enumerate()
関数を使う。
for index, value in enumerate(listA):
print(f"{index}: {value}")
# output
# 0: 1
# 1: 2
# 2: 3
# 3: 4
# 4: 5
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=0、2、4だけを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
の場合、index
ではなく、key-value pair
を取りたいですね。
その時に、items()
関数を使う。
for key, value in dictA.items():
print(f"{key}: {value}")
# output
# a1: 1
# a2: 2
# a3: 3
# a4: 4
# a5: 5
一つのリストを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の回数は短いリストの要素数になると思う。)
例えば、listAの要素を全て2倍になるリストが欲しい場合、map
関数利用すると簡単にできる。
listAx2 = list(map(lambda x: x * 2, listA))
map関数の例のようにリスト内包表記でも同じことができる。
listAx2 = [ x*2 for x in listA]
for in
の記述、zip
関数、map
関数でloopができる。enumerate
関数でlist
とdist
をloopする際に、index
、key-value
を取得することが可能。