简体   繁体   English

关于 Python 元组拆包的说明

[英]Clarifications on Python tuple unpacking

It's understood that unpacking of a tuple can happen only between tuples/list so据了解,元组的解包只能发生在元组/列表之间,所以

x,*y = (1,2,3,4)

is valid.已验证。 However, if we try to do the unpacking on a single variable但是,如果我们尝试对单个变量进行解包

*x = (1,2,3,4,5)

we get an error as x is not a list/tuple hence unpacking cannot occur.我们收到一个错误,因为 x 不是列表/元组,因此无法进行解包。 If that is the case then how can we use *args to have multiple parameters in function如果是这种情况,那么我们如何使用 *args 在 function 中有多个参数

def max(* args):
  for x in args:
    print(x)

So here if I call max(1,2,3,4).所以在这里,如果我调用 max(1,2,3,4)。 Shouldn't we get an error coz *args is not a tuple therefore we can't do unpacking?我们不应该得到一个错误因为 *args is not a tuple 因此我们不能解包吗?

The catch is that the brackets of a parameter list always enclose a tuple.问题是参数列表的括号总是包含一个元组。 They are brackets you could not omit .它们是您不能省略的括号。 So they are not mixed up with operator-priority-brackets因此它们不会与运算符优先级括号混淆

By the way, fun fact: write (NOTE THE COMMA AFTER THE x)顺便说一句,有趣的事实:写(注意 x 之后的逗号)

*x, = (1,2,3,4,5)

Then it works, just like you would neet to add a comma in a bracket to make it a tuple.然后它就可以工作了,就像您需要在括号中添加一个逗号以使其成为一个元组一样。 like (1) is no tuple, but (1,) is像 (1) 不是元组,但 (1,) 是

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM