python--字典、列表的遍历技巧

1.在字典中进行遍历的时候可以采用item()方法将字典中的键值对同时遍历出来:

示例如下:

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

2.在列表中遍历时采用enumerate()方法将索引位置和对应值同时得到:

示例如下:

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

3.同时遍历两个或更多的序列可使用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.

转载自:http://www.runoob.com/python3/python3-data-structure.html

 

你可能感兴趣的:(自学ing)