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

Do python#39;s variable length arguments (*args) expand a generator at function call time?(python的可变长度参数(*args)是否在函数调用时扩展生成器?)

本文介绍了python的可变长度参数(*args)是否在函数调用时扩展生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 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')

这篇关于python的可变长度参数(*args)是否在函数调用时扩展生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐