在Python中,可迭代对象是指那些可以直接用于`for`循环中,通过迭代器机制来访问其元素的对象。常见的可迭代对象包括:
列表 (list)
L = list(range(100))
for i in L:
print(i)
元组 (tuple)
T = tuple(range(100))
for i in T:
print(i)
字典 (dict)
dic = {'name': 'chen', 'age': 25, 'loc': 'Tianjin'}
for key in dic:
print(key)
for value in dic.values():
print(value)
for key, value in dic.items():
print(key, value)
字符串 (str)
S = 'Say YOLO Again!'
for s in S:
print(s)
集合 (set)
注意:集合在Python 3.x中是不可变的,因此不能直接迭代
但是可以使用生成器表达式来间接迭代
set_example = {1, 2, 3, 4, 5}
for item in set_example:
print(item)
range对象
for i in range(100):
print(i)
可迭代对象具有`__iter__()`方法,该方法返回一个迭代器对象,该对象定义了`__next__()`方法,用于获取序列中的下一个值。
需要注意的是,集合在Python 3.x中是不可变的,因此不能直接迭代。但是可以使用生成器表达式来间接迭代集合中的元素。