如果我们考虑以下生成器和生成器函数:
def integers():
"""Infinite sequence of integers."""
i = 1
while True:
yield i
i = i + 1
def take(n, seq):
"""Returns first n values from the given sequence."""
seq = iter(seq)
result = []
try:
for i in range(n):
result.append(seq.next())
except StopIteration:
pass
return result
print take(5, integers()) # prints [1,2,3,4,5]
为什么生成器函数中必须调用内置的iter函数?如果没有它,代码仍然会运行并打印正确的值。
最佳答案
take
不知道它接收的是迭代器(例如生成器)还是容器(例如列表/元组/集合)。在后一种情况下,容器没有与之关联的 .next
方法,因此您的代码将会失败。您的代码是谨慎行事而不是冒险,我认为这是良好的编程实践。
一个例子(python3):
def foo():
yield from [1, 2, 3]
x = iter([1, 2, 3])
y = iter(foo())
print( next(x), next(y) ) # this would be `x.next()` in python2
(1, 1)
在后一种情况下,iter 是多余的,但代码在这两种情况下都可以工作。但是,请考虑:
x = [1, 2, 3]
print(next(x))
TypeError Traceback (most recent call last)
<ipython-input-351-cf05c93171ef> in <module>()
----> 1 print(next(x))
TypeError: 'list' object is not an iterator
应该清楚为什么需要 iter
调用。
关于python - 为什么将生成器传递给 iter 来使用它的生成器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46017899/