在Python中,可迭代对象(Iterable) 是指可以被遍历(例如用 for
循环逐项访问)的对象,而 不可迭代对象(Non-Iterable) 无法直接遍历。以下是详细分类和示例:
可迭代对象需要实现 __iter__()
方法,或支持通过索引访问的 __getitem__()
方法。常见类型包括:
list
):[1, 2, 3]
tuple
):(1, 2, 3)
str
):"hello"
dict
):{"a": 1, "b": 2}
(遍历键)set
):{1, 2, 3}
TextIO
):逐行遍历内容。with open("file.txt") as f:
for line in f: # 逐行读取
print(line)
生成器函数(使用 yield
):
def count(n):
i = 0
while i < n:
yield i
i += 1
for num in count(5):
print(num) # 输出 0,1,2,3,4
生成器表达式:
squares = (x**2 for x in range(5)) # 可迭代
range
对象:range(5)
enumerate
):enumerate(["a", "b"])
zip
对象:zip([1,2], [3,4])
__iter__()
或 __getitem__()
):class MyIterable:
def __iter__(self):
return iter([1, 2, 3])
for item in MyIterable():
print(item) # 输出 1,2,3
不可迭代对象通常是简单数据类型或未实现迭代协议的对象。例如:
int
):5
float
):3.14
bool
):True
(虽然 bool
是 int
的子类,但不可迭代)None
:None
def f(): pass
→ f
不可迭代import math
→ math
不可迭代__iter__
)。iter()
函数如果对象不可迭代,会抛出 TypeError
:
obj = 123
try:
iter(obj) # 触发 TypeError
except TypeError:
print("不可迭代")
isinstance()
和 Iterable
更规范的检测方式:
from collections.abc import Iterable
print(isinstance([1,2,3], Iterable)) # True
print(isinstance(123, Iterable)) # False
__next__()
方法,用于逐个返回元素(如生成器)。iter()
转换。my_list = [1, 2, 3]
iterator = iter(my_list) # 转为迭代器
print(next(iterator)) # 输出 1
# 遍历字典的键值对
d = {"a": 1, "b": 2}
for key, value in d.items():
print(key, value)
num = 100
for x in num: # 触发 TypeError: 'int' is not iterable
print(x)
类型 | 可迭代 | 示例 |
---|---|---|
列表、元组、字符串 | ✔️ | [1, 2] , "abc" |
字典、集合 | ✔️ | {"a": 1} , {1, 2} |
生成器、文件对象 | ✔️ | (x for x in range(3)) |
整数、浮点、None | ❌ | 123 , 3.14 , None |
理解可迭代对象是掌握Python循环、生成器、推导式等高级用法的关键!