5.6. 循环的技巧

当在字典中循环时,用 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.

当逆向循环一个序列时,先正向定位序列,然后调用 reversed() 函数

  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]