首页 > 编程语言 > 详细

python 循环技巧

时间:2015-03-05 16:38:47      阅读:374      评论:0      收藏:0      [点我收藏+]

 

原文地址:http://docs.pythontab.com/python/python3.4/datastructures.html#tut-tuples

 

在字典中循环时,关键字和对应的值可以使用 iteritems() 方法同时解读出来。

knights = {gallahad: the pure, robin: the brave}
 
for k,v in knights.items():
    print(k,v)

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

robin the brave
gallahad the pure

 

在序列中循环时,索引位置和对应值可以使用 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("{0},{1}".format(q,a))


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

name,lancelot
quest,the holy grail
favorite color,blue

 

需要逆向循环序列的话,先正向定位序列,然后调用 reversed() 函数。

for i in reversed(range(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

 

python 循环技巧

原文:http://www.cnblogs.com/nzyjlr/p/4316052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!