Do python#39;s variable length arguments (*args) expand a generator at function call time?(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)是否在函数调用时扩展生成器?


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01