>>> from collections import Iterable
>>> isinstance('aaa', Iterable)
True
>>>
1、list的迭代
>>> L
[1, 2, 3, 4]
>>> for n in L:
... print(n)
...1234
>>>
2、tuple的迭代
>>> t = (1,2,3)
>>> for n in t:
... print(n)
...123
>>>
3、dic的迭代
>>> dic = {'a':1, 'b':2, 'c':3}
>>> for n in dic:
... print(n) #打印每个key...
a
b
c
>>> for v in dic.values():
... print(v) #打印每个value...123
>>> for k,v in dic.items():
... print(k,v) #同时打印每个key和对应value...
a 1
b 2
c 3
>>>
4、字符串的迭代
>>> for n in'abcd':
... print(n)
...
a
b
c
d
5、需要迭代索引的时候,可以使用enumerate()函数
>>> for n in enumerate(['a', 'b', 'c', 'd']):
... print(n)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
>>> for i,v in enumerate(['a', 'b', 'c', 'd']):
... print(i,v)
...0 a
1 b
2 c
3 d
6、还可以同时迭代多个引用变量
>>> for a, b, c in [(1, 2, 3), (4, 5, 6), (7, 8, 9)]:
... print(a, b, c) #同时打印三个变量...123456789
>>> for a, b in [(1, 2), (4, 5), (7, 8)]:
... print(a, b) #同时打印两个变量...124578
>>>
>>>> for a, b, c in [(1, 2), (4, 5), (7, 8)]:
... print(a, b) #参数对不上会报错...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)