5.6 循环技术

当循环字典的时候,key 和对应的值可以通过 items() 方法同时获取。

  1. >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
  2. >>> for k, v in knights.items():
  3. ... print(k, v)
  4. ...
  5. gallahad the pure
  6. robin the brave

当循环序列的时候,索引的位置和对应的值可以通过 enumerate() 函数同时获取。

  1. >>> for i, v in enumerate(['tic', 'tac', 'toe']):
  2. ... print(i, v)
  3. ...
  4. 0 tic
  5. 1 tac
  6. 2 toe

同时循环两个以上序列的时候,这些条目可以使用 zip() 函数来配对。

  1. >>> questions = ['name', 'quest', 'favorite color']
  2. >>> answers = ['lancelot', 'the holy grail', 'blue']
  3. >>> for q, a in zip(questions, answers):
  4. ... print('What is your {0}? It is {1}.'.format(q, a))
  5. ...
  6. What is your name? It is lancelot.
  7. What is your quest? It is the holy grail.
  8. What is your favorite color? It is blue.

在一个相反的序列内循环的时候,首先指定循环方向的序列,然后调用 reverse() 函数。

  1. >>> for i in reversed(range(1, 10, 2)):
  2. ... print(i)
  3. ...
  4. 9
  5. 7
  6. 5
  7. 3
  8. 1

在一个排列好的的序列内循环,可以使用 sorted() 函数,这个函数会返回一个新的排序好的列表,而保持原来的列表不变。

  1. >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
  2. >>> for f in sorted(set(basket)):
  3. ... print(f)
  4. ...
  5. apple
  6. banana
  7. orange
  8. pear

在你一边循环一个列表的时一边候改变它,有时候着具有吸引力。但是创建一个新列表会更简单安全。

  1. >>> import math
  2. >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
  3. >>> filtered_data = []
  4. >>> for value in raw_data:
  5. ... if not math.isnan(value):
  6. ... filtered_data.append(value)
  7. ...
  8. >>> filtered_data
  9. [56.2, 51.7, 55.3, 52.5, 47.8]