# Looping Techniques

## Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method.

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

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

 >>> for i, v in enumerate(['tic', 'tac', 'toe']):...     print i, v...0 tic1 tac2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>> 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.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>> for i in reversed(xrange(1,10,2)):...     print i...97531

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):...     print f... 	applebananaorangepear
• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
03-10 1352
04-20 9979
12-19 1295
02-23 1342
02-26 310
02-27 83
02-26 263
02-26 514
02-27 142
02-27 195

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。