如果給定一個list或tuple,可以使用for回圈來遍歷,這種遍歷稱為迭代(Iteration),python中的迭代是通過for...in 來完成,不僅可迭代list/tuple,還可迭代其他物件,
# 迭代list
>>> l = list(range(10))
>>> for item in l:
... print(item)
# 迭代dict,由于dict的存盤不是像list那樣順序存盤,所有迭代結果可能不是按順序的
>>> d = {'a':1, 'b':2}
>>> for key in d: # 默認是迭代的key
... print(key)
...
b
a
>>> for value in d.values(): # 迭代value
... print(value)
...
2
1
>>> for k,v in d.items(): # 迭代key和value
... print(k, v)
...
b 2
a 1
# 迭代字串
>>> for ch in 'abc':
... print(ch)
...
a
b
c
當使用for時,只要作用與一個迭代物件,就可以正常運行,我們不需要關注迭代物件是list還是其他資料型別,可以通過collections模塊的Iterable型別判斷一個物件是否是可迭代物件:
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str型別可迭代
True
>>> isinstance(123, Iterable) # 整數不可迭代
False
>>> dict={'a':1}
>>> isinstance(dict, Iterable) # dict型別可迭代
True
python內置的enumerate函式可以將list變成索引-元素對,這樣可以在for中迭代索引和物件本身:
>>> l = ['a','b','c','d']
>>> for i,value in enumerate(l):
... print(i, value)
...
0 a
1 b
2 c
3 d
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/157921.html
標籤:Python
上一篇:判斷IP地址的合法性
下一篇:使用泰勒級數公式計算圓周率
