在 Python 中传递具有多个返回值作为参数的函数 [英] Passing functions which have multiple return values as arguments in Python
问题描述
因此,Python 函数可以返回多个值.我突然想到,如果以下可能的话,它会很方便(虽然可读性稍差).
So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
a = [[1,2],[3,4]]
def cord():
return 1, 1
def printa(y,x):
print a[y][x]
printa(cord())
...但事实并非如此.我知道您可以通过将两个返回值都转储到临时变量中来做同样的事情,但它看起来并不优雅.我也可以将最后一行重写为printa(cord()[0],cord()[1])",但这会执行cord()两次.
...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.
有没有一种优雅、有效的方法来做到这一点?或者我应该只看到关于过早优化的引用而忘记这一点?
Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?
推荐答案
printa(*cord())
这里的 *
是一个参数扩展运算符……好吧,我忘记了它的技术名称,但在这种情况下,它需要一个列表或元组并将其扩展出来,以便函数看到每个列表/元组元素作为单独的参数.
The *
here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
它基本上是 *
的反面,您可能会使用它来捕获函数定义中的所有非关键字参数:
It's basically the reverse of the *
you might use to capture all non-keyword arguments in a function definition:
def fn(*args):
# args is now a tuple of the non-keyworded arguments
print args
fn(1, 2, 3, 4, 5)
打印(1, 2, 3, 4, 5)
fn(*[1, 2, 3, 4, 5])
做同样的事情.
这篇关于在 Python 中传递具有多个返回值作为参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!