ループのテクニック

  • 辞書に対してループを行う際、 
    items() メソッドを使うと、キーとそれに対応する値を同時に取り出せます。
In [1]:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)
gallahad the pure
robin the brave
  • シーケンスにわたるループを行う際、 
    enumerate() 関数を使うと、要素のインデックスと要素を同時に取り出すことができます。
In [2]:
for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)
0 tic
1 tac
2 toe
  • 二つまたはそれ以上のシーケンス型を同時にループするために、 
    関数 zip() を使って各要素をひと組みにすることができます。
In [3]:
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
  • シーケンスを逆方向に渡ってループするには、 
    まずシーケンスの範囲を順方向に指定し、次いで関数 reversed() を呼び出します。
In [4]:
for i in reversed(range(1, 10, 2)):
    print(i)
9
7
5
3
1
  • シーケンスをソートされた順序でループするには、 
    sorted() 関数を使います。この関数は元の配列を変更せず、ソート済みの新たな配列を返します。
In [5]:
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
    print(f)
apple
banana
orange
pear

ループ内でリストを変更することも可能ですが、代わりに新しいリストを作ったほうがより簡単で安全でしょう。

In [6]:
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
    if not math.isnan(value):
        filtered_data.append(value)

print(filtered_data)
[56.2, 51.7, 55.3, 52.5, 47.8]