空元组(takewhile())是否在推进我的Python迭代器?

2024-06-09 18:14:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: 对象lambdafalsemydef情况rangelist
1条回答
网友
1楼 · 发布于 2024-06-09 18:14:34

您的问题可以简化为:

In [9]: expected = range(5)

In [10]: surprise = iter([0, 1, 2, 3, 4])

In [11]: list(expected)
Out[11]: [0, 1, 2, 3, 4]

In [12]: list(expected)
Out[12]: [0, 1, 2, 3, 4]

In [13]: list(surprise)
Out[13]: [0, 1, 2, 3, 4]

In [14]: list(surprise)
Out[14]: []

这是因为range是一个对象,每次有人调用__iter__时,它都会生成新的迭代器:

In [19]: expected.__iter__() is expected.__iter__()
Out[19]: False

但是,在迭代器上调用__iter__将始终返回相同的对象:

In [18]: surprise.__iter__() is surprise.__iter__()
Out[18]: True

这意味着您只能在迭代器对象上迭代一次

相关问题 更多 >