Python中的可迭代對象有:列表、元組、字典、字符串;常結合for循環使用;
判斷一個對象是不是可迭代對象:
from collections import Iterable
isinstance(list(range(100)), Iterable)
isinstance('Say YOLO Again.')
列表:
L = list(range(100))
for i in L:
print(i)
元組:
T = tuple(range(100))
for i in T:
print(i)
字典:
dic = {'name': 'chen', 'age': 25, 'loc': 'Tianjin'}
# 以列表的形式返回key
list(dic.keys())
# 以列表的形式返回value
list(dic.values())
# 循環key
for key in dic:
print(key)
# 循環value
for value in dic.values():
print(value)
# 循環key, value
for key, value in dic.items():
print(key, value)
字符串:
S = 'Say YOLO Again!'
for s in S:
print(s)
返回'索引-元素'對:
for i, value in enumerate('Say YOLO Again.'):
print(i, value)