概述 for v in d.values(): for k,v in d.items(): for a in 'adfa': #判斷對象是否可迭代 from collections import Iterable isinstance('abc',Iterable) #添加下標 for x,y in ...
概述
for v in d.values():
for k,v in d.items():
for a in 'adfa':
#判斷對象是否可迭代
from collections import Iterable
isinstance('abc',Iterable)
#添加下標
for x,y in enumerate([(1,1),(2,3),(4,5)]):
詳解
1.迭代list
>>> d={'a':1,'b':2,'c':3}
#輸出values
>>> for v in d.values():
... print v
...
1
3
2
#同時輸出key,value
>>> for k, v in d.items(): ... print k,v ... #輸出 a 1 c 3 b 2
2.字元串迭代
>>> for a in 'adfa': ... print a ... a d f a
3.判斷一個對象是否可迭代
>>>from collections import Iterable #判斷字元串是否可迭代 >>>isinstance('abc',Iterable) #輸出 True
#判斷list是否可迭代
>>>isinstance([1,2,3],Iterable)
#輸出
True
#判斷整數是否可迭代
>>> isinstance(12345,Iterable)
False
4.對list實現下標迴圈
>>> for i,value in enumerate(['a','b','c']): ... print(i,value) ... (0, 'a') (1, 'b') (2, 'c') >>> for i,value in enumerate(['a','b','c']): ... print i,value ... 0 a 1 b 2 c
>>> for x,y in [(1,1),(2,3),(4,5)]: ... print x,y ... 1 1 2 3 4 5
>>> for x,y in enumerate([(1,1),(2,3),(4,5)]):
... print x,y
...
0 (1, 1)
1 (2, 3)
2 (4, 5)