迭代器是一种可以遍历集合对象的数据结构。在 Python 中,迭代器提供了一种访问集合元素的方式,而无需暴露其底层表示。迭代器对象实现了 __iter__() 和 __next__() 方法。
创建迭代器
要创建一个迭代器,需要实现 __iter__() 和 __next__() 方法。__iter__() 方法返回迭代器对象本身,而 __next__() 方法会返回容器中的下一个值。如果容器中没有更多元素,则会引发 StopIteration 异常。
// www.javascriptcn.com code example
class MyIterator:
def __init__(self, max):
self.max = max
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.max:
value = self.current
self.current += 1
return value
else:
raise StopIteration
my_iter = MyIterator(5)
for i in my_iter:
print(i)使用内置的迭代器
Python 内置了许多可迭代的对象,例如列表、元组、字典、集合等。这些可迭代对象都支持迭代协议,可以通过内置的 iter() 函数获取它们的迭代器。
列表迭代
列表是一个常见的可迭代对象。可以通过 for 循环遍历列表中的元素。
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)字典迭代
字典是一个键值对的集合。可以通过 for 循环遍历字典的键或值。
// www.javascriptcn.com code example
my_dict = {"name": "Alice", "age": 25}
for key in my_dict:
print(key)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(f"{key}: {value}")集合迭代
集合是一个无序且不重复的元素集合。可以通过 for 循环遍历集合中的元素。
my_set = {1, 2, 3, 4, 5}
for item in my_set:
print(item)生成器
生成器是一种特殊的迭代器,使用 yield 关键字来返回数据。生成器函数在每次调用 next() 时会从上次停止的地方继续执行,而不是从头开始。
基本生成器
生成器函数通过 yield 关键字返回值,每次调用生成器函数都会生成一个新的生成器对象。
// www.javascriptcn.com code example
def simple_generator():
yield 1
yield 2
yield 3
gen = simple_generator()
print(next(gen)) # 输出: 1
print(next(gen)) # 输出: 2
print(next(gen)) # 输出: 3带状态的生成器
生成器可以在函数体内保持状态,并在每次调用时继续执行。
// www.javascriptcn.com code example
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for number in counter:
print(number)生成器表达式
生成器表达式类似于列表推导式,但使用圆括号 () 而不是方括号 []。生成器表达式会按需生成元素,而不是一次性生成所有元素。
squares = (x * x for x in range(10))
for square in squares:
print(square)生成器方法
生成器对象还具有一些方法,如 send()、throw() 和 close(),可以用来控制生成器的执行。
send() 方法
send() 方法允许向生成器发送值,并将该值作为 yield 表达式的返回值。
def echo_value():
while True:
value = yield
print(f"Received: {value}")
generator = echo_value()
next(generator) # 启动生成器
generator.send("Hello") # 输出: Received: Hellothrow() 方法
throw() 方法允许在生成器内部引发异常。
// www.javascriptcn.com code example
def generator_with_exception():
try:
yield "First"
yield "Second"
except ValueError:
yield "Exception Handled"
gen = generator_with_exception()
print(next(gen)) # 输出: First
print(gen.throw(ValueError)) # 输出: Exception Handledclose() 方法
close() 方法允许停止生成器的执行。
// www.javascriptcn.com code example
def generator_with_close():
try:
while True:
yield "Continuing"
except GeneratorExit:
print("Generator closed")
gen = generator_with_close()
next(gen) # 输出: Continuing
gen.close() # 输出: Generator closed迭代器和生成器的应用
迭代器和生成器在处理大数据集和无限序列时非常有用。它们允许程序逐个处理元素,而不必一次性加载整个数据集到内存中。
处理大数据集
在处理大量数据时,可以使用生成器来避免内存不足的问题。
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line
for line in read_large_file('large_file.txt'):
process(line)无限序列
生成器还可以用于创建无限序列,只要在适当的时候停止生成即可。
// www.javascriptcn.com code example
def infinite_sequence():
num = 0
while True:
yield num
num += 1
counter = infinite_sequence()
for _ in range(10):
print(next(counter))通过上述内容,我们了解了迭代器和生成器的基本概念和应用。这些工具为处理复杂的数据集和实现高效的代码提供了强大的支持。