1.在Python中,迭代是通过for ... in来完成的,Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上,比如字典,字符串等

for ch in 'ABC':
...     print(ch)
...
A
B
C

2.要对某对象使用迭代,只需判断其是不是可迭代对象即可。

>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True

3.python 可以同时迭代两个变量

>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9

>>> for i, value in enumerate(['A', 'B', 'C']): //迭代list下标和对应元素
...     print(i, value)
...
0 A
1 B
2 C
posted on 2019-07-03 16:31  大杰杰  阅读(72)  评论(0编辑  收藏  举报