python 的可变长度参数 (*args) 是否在函数调用时扩展生成器?
考虑以下 Python 代码:
def f(*args):
for a in args:
pass
foo = ['foo', 'bar', 'baz']
# Python generator expressions FTW
gen = (f for f in foo)
f(*gen)
*args
是否在调用时自动扩展生成器?换句话说,我是否在 f(*gen)
内迭代 gen
两次,一次扩展 *args
一次迭代 args?或者生成器是否保持原始状态,而迭代仅在 for 循环期间发生一次?
Consider the following Python code:
def f(*args):
for a in args:
pass
foo = ['foo', 'bar', 'baz']
# Python generator expressions FTW
gen = (f for f in foo)
f(*gen)
Does *args
automatically expand the generator at call-time? Put another way, am I iterating over gen
twice within f(*gen)
, once to expand *args
and once to iterate over args? Or is the generator preserved in pristine condition, while iteration only happens once during the for loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
生成器在函数调用时展开,您可以轻松检查:
将打印
The generator is expanded at the time of the function call, as you can easily check:
will print
为什么不看看
f()
中的gen
是什么?添加print args
作为第一行。如果它仍然是一个生成器对象,它会告诉你。我希望参数解包将其变成一个元组。Why not look and see what
gen
is inf()
? Addprint args
as the first line. If it's still a generator object, it'll tell you. I would expect the argument unpacking to turn it into a tuple.你并不真正需要
Calling
将输出
Your don't really need
Calling
will output