lists = [1, 2, 3, 4, 5] for i in lists: print(i)
dicts = { "a": 1, "b": 2 } for i in dicts: print(i) # 輸出結果 a b
from collections import Iterable lists = [1, 2, 3, 4, 5] dicts = { "a": 1, "b": 2 } print(isinstance(lists, Iterable)) print(isinstance(dicts, Iterable)) print(isinstance({"test"}, Iterable)) print(isinstance(1234, Iterable)) # 輸出結果 True True True False
lists = [1, 2, 3, 4, 5] # 看看是否是迭代對象 print(isinstance(enumerate(lists), Iterable)) # 循環 for ind, val in enumerate(lists): print(ind, val) # 輸出結果 True 0 1 1 2 2 3 3 4 4 5
for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y) # 輸出結果 1 1 2 4 3 9
任何可迭代對象均可以做用於 for 循環,包括咱們自定義的數據類型,只要符合迭代條件,就能夠使用 for 循環函數