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

2022-01-24 00:00:00 python generator function iteration

问题描述

考虑以下 Python 代码:

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)

*args 会在调用时自动扩展生成器吗?换句话说,我是否在 f(*gen) 内对 gen 进行了两次迭代,一次是展开 *args,一次是对 args 进行迭代?还是生成器保持原始状态,而迭代只在 for 循环中发生一次?

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?


解决方案

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

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)

将打印

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

相关文章