5.6. Looping Techniques(循环技术)

来源:互联网 发布:伊藤开司 知乎 编辑:程序博客网 时间:2024/06/05 21:16

遍历序列时,用 enumerate()函数可以同时得到序列中元素的下标和元素值。

>>> for i, v in enumerate(['tic', 'tac', 'toe']):...     print i, v...0 tic1 tac2 toe

若想一次遍历多个序列,可以用 zip()函数。

>>> 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()函数。

>>> for i in reversed(xrange(1,10,2)):...     print i...97531

想要按序遍历洗了,用sorted()函数,将会返回一个按序序列的副本,而不会改变原序列。

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):...     print f...applebananaorangepear

在遍历字典的时候,可以用iteritems()方法同时获得元素的键和值。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.iteritems():...     print k, v...gallahad the purerobin the brave

有时候你可能会尝试在遍历列表的时候改变该列表;然而,更简单又安全的方式是创建一个新列表。

>>> 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)...>>> filtered_data[56.2, 51.7, 55.3, 52.5, 47.8]


译者小结:

reversed()返回一个序列的反向迭代器,而sorted返回一个新的有序列表。不要再遍历列表的时候同时改变它。

0 0
原创粉丝点击