python 的可变长度参数 (*args) 是否在函数调用时扩展生成器?

发布于 2024-10-20 10:11:20 字数 356 浏览 1 评论 0原文

考虑以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月无声 2024-10-27 10:11:20

生成器在函数调用时展开,您可以轻松检查:

def f(*args):
    print(args)
foo = ['foo', 'bar', 'baz']
gen = (f for f in foo)
f(*gen)

将打印

('foo', 'bar', 'baz')

The generator is expanded at the time of the function call, as you can easily check:

def f(*args):
    print(args)
foo = ['foo', 'bar', 'baz']
gen = (f for f in foo)
f(*gen)

will print

('foo', 'bar', 'baz')
一瞬间的火花 2024-10-27 10:11:20

为什么不看看 f() 中的 gen 是什么?添加 print args 作为第一行。如果它仍然是一个生成器对象,它会告诉你。我希望参数解包将其变成一个元组。

Why not look and see what gen is in f()? Add print 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.

烛影斜 2024-10-27 10:11:20

你并不真正需要

gen = (f for f in foo)

Calling

f(*foo)

将输出

('foo', 'bar', 'baz')

Your don't really need

gen = (f for f in foo)

Calling

f(*foo)

will output

('foo', 'bar', 'baz')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文