在 Python 中传递具有多个返回值作为参数的函数
因此,Python 函数可以返回多个值。 我突然意识到,如果可以实现以下内容,那就会很方便(尽管可读性稍差)。
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() 两次。
有没有一种优雅、有效的方法来做到这一点? 或者我应该只看到有关过早优化的引用并忘记这一点?
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())
...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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的
*
是一个参数扩展运算符...好吧,我忘记了它在技术上的名称,但在这种情况下,它需要一个列表或元组并将其扩展出来,以便该函数将每个列表/元组元素视为一个单独的论点。它基本上与您可能用来捕获函数定义中所有非关键字参数的
*
相反:prints
(1, 2, 3, 4, 5)
执行以下操作:相同的。
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:prints
(1, 2, 3, 4, 5)
does the same.
试试这个:
星号基本上是说“使用这个集合的元素作为位置参数”。 您可以使用两个星号对关键字参数的字典执行相同的操作:
Try this:
The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:
实际上,Python 并不真正返回多个值,它返回一个值,该值可以是打包到一个元组中的多个值。 这意味着您需要“解压”返回值才能获得多个值。
像这样的语句
可以做到这一点,但是像您那样直接使用返回值
则不会,这就是您需要使用星号的原因。 也许一个很好的术语是“隐式元组解包”或“无分配的元组解包”。
Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples.
A statement like
does that, but directly using the return value as you did in
doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".