Python 3.5.4版
如果我向takewhile传递一个list_迭代器,然后在takewhile对象上迭代,那么list_迭代器是高级的,即使takewhile对象什么都不取。当我将range对象传递给takewhile时,不会发生这种情况。如果这是预期的行为,那么我有东西要学
def range_vs_iter():
# expected works as expected. surprise does not.
expected = range(5)
surprise = iter([0, 1, 2, 3, 4])
# both of these produce an empty tuple
print(tuple(takewhile(lambda x: False, expected)))
print(tuple(takewhile(lambda x: False, surprise)))
# the first element in surprise has disappeared
print(tuple(expected)) # (0, 1, 2, 3, 4)
print(tuple(surprise)) # (1, 2, 3, 4)
# if I don't iterate over takewhile object, everything is fine
my_iter = iter([0, 1, 2, 3, 4])
takewhile(lambda x: False, my_iter)
print(tuple(my_iter)) # (0, 1, 2, 3, 4)
您的问题可以简化为:
这是因为
range
是一个对象,每次有人调用__iter__
时,它都会生成新的迭代器:但是,在迭代器上调用
__iter__
将始终返回相同的对象:这意味着您只能在迭代器对象上迭代一次
相关问题 更多 >
编程相关推荐