码迷,mamicode.com
首页 > 编程语言 > 详细

python中遍历的技巧

时间:2016-03-21 23:02:41      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

遍历的技巧

遍历一个序列时,使用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

若要在循环内部修改正在遍历的序列(例如复制某些元素),建议您首先制作副本。在序列上循环不会隐式地创建副本。切片表示法使这尤其方便:

>>> words = [‘cat‘, ‘window‘, ‘defenestrate‘]
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
[‘defenestrate‘, ‘cat‘, ‘window‘, ‘defenestrate‘]

python中遍历的技巧

标签:

原文地址:http://www.cnblogs.com/steval/p/5304156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!