您的位置:首页 > 编程语言 > Python开发

python 循环技巧

2015-03-05 15:53 225 查看
原文地址:http://docs.pythontab.com/python/python3.4/datastructures.html#tut-tuples在字典中循环时,关键字和对应的值可以使用iteritems()方法同时解读出来。
knights={'gallahad':'thepure','robin':'thebrave'}

fork,vinknights.items():
print(k,v)

-------输出如下-------------------------

robinthebrave
gallahadthepure在序列中循环时,索引位置和对应值可以使用enumerate()函数同时得到。
fori,vinenumerate(['tic','tac','toe']):
print(i,v)

------输出如下------------------------------

0tic
1tac
2toe
同时循环两个或更多的序列,可以使用zip()整体打包。
questions=['name','quest','favoritecolor']
answers=['lancelot','theholygrail','blue']forq,ainzip(questions,answers):
print("{0},{1}".format(q,a))------输出如下----------------------------------

name,lancelot
quest,theholygrail
favoritecolor,blue需要逆向循环序列的话,先正向定位序列,然后调用reversed()函数。
foriinreversed(range(1,10,2)):
print(i)

------输出如下----------------------------------

9
7
5
3
1
要按排序后的顺序循环序列的话,使用sorted()函数,它不改动原序列,而是生成一个新的已排序的序列.
basket=['apple','orange','apple','pear','orange','banana']forfinsorted(set(basket)):
print(f)

------输出如下----------------------------------

apple
banana
orange
pear
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: