您的位置:首页 > 产品设计 > UI/UE

5.6. Looping Techniques(循环技术)

2016-01-11 15:00 435 查看
遍历序列时,用 enumerate()函数可以同时得到序列中元素的下标和元素值。

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 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
...
9
7
5
3
1

想要按序遍历洗了,用sorted()函数,将会返回一个按序序列的副本,而不会改变原序列。
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear

在遍历字典的时候,可以用iteritems()方法同时获得元素的键和值。
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin 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返回一个新的有序列表。不要再遍历列表的时候同时改变它。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 循环