gpt4 book ai didi

python - print(*generator, ) 的不同行为

转载 作者:行者123 更新时间:2023-12-04 08:15:24 26 4
gpt4 key购买 nike


请帮助理解为什么这两种情况虽然都使用生成器 (i for i in range(5)) 却表现不同.

>>> print(i for i in range(5))
<generator object <genexpr> at 0x7fc409c02900>
>>> print(*(i for i in range(5)))
0 1 2 3 4
>>> print(*(i for i in range(5)), 5)
0 1 2 3 4 5
>>> _r = (i for i in range(5))
>>> print(_r)
<generator object <genexpr> at 0x7fc409c029e0>
>>> print(*_r)
0 1 2 3 4
>>> print(*_r, 5)
5
>>> print(*(_r), 5)
5

最佳答案

当您使用 *生成器表达式(或任何迭代器)上的运算符,它使用它:

my_iterator = (i for i in range(3))

second_iterator = iter(list(range(3)))

# splat operator consumes the generator expression
print(*my_iterator)
0 1 2
print(*my_iterator, "Empty!")
Empty!

# splat operator also consumes the iterator
print(*second_iterator)
0 1 2
print(*second_iterator, "Also empty!")
Also empty!
您需要重新创建它以重新使用它,这就是您在第一个示例中所做的:
s = (i for i in range(3))
print(*s)
0 1 2

# You create a new generator expression/iterator
s = (i for i in range(3))
print(*s)
0 1 2

# And so it isn't empty
# same with the shorthand
print(*(i for i in range(3))
0 1 2
关于 range 的注释
因为我用过 range对于这个例子,重要的是要注意 range不共享此行为,而是在 range 上的迭代器做:
x = range(3)

print(*x)
0 1 2

print(*x)
0 1 2
# the range object isn't consumed and can be re-used

a = iter(x)

print(*a)
0 1 2

print(*a)

# prints nothing because `a` has been exhausted
更多详情请见 this answer

关于python - print(*generator, <element>) 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65730602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com