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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)