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

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

问题描述

考虑以下Python代码:

  def f(* args):
for a args:
通过

foo = ['foo','bar','baz']

#Python生成器表达式FTW
gen =(f for f在foo中)

f(* gen)

* args 在通话时自动扩展发生器?换一种说法,我在 f(* gen)中迭代 gen 两次,展开 * args 并且一次迭代args?或者是生成器保持原始状态,而迭代只在for循环中发生一次?解析方案

生成器在函数调用的时间,因为你可以很容易地检查:

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




$ b $ p $ ('foo' ,'bar','baz')


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?

解决方案

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')

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆