python循环技巧

来源:互联网 发布:windows多线程编程视频 编辑:程序博客网 时间:2024/05/22 10:23

python循环技巧

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

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

在序列中循环时,索引位置和对应值可以使用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 %s?  It is %s.' % (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.
0 0
原创粉丝点击