本文介绍了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)是否在函数调用时扩展生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)