Python 简明教程
Python - Unpack Tuple Items
Unpack Tuple Items
The term "unpacking" refers to the process of parsing tuple items in individual variables. In Python, the parentheses are the default delimiters for a literal representation of sequence object.
声明元组的以下语句是相同的。
Following statements to declare a tuple are identical.
>>> t1 = (x,y)
>>> t1 = x,y
>>> type (t1)
<class 'tuple'>
Example
若要将元组项存储在单独的变量中,请在赋值运算符的左侧使用多个变量,如此处所示 −
To store tuple items in individual variables, use multiple variables on the left of assignment operator, as shown in the following example −
tup1 = (10,20,30)
x, y, z = tup1
print ("x: ", x, "y: ", "z: ",z)
它将生成以下 output −
It will produce the following output −
x: 10 y: 20 z: 30
这就是在单独变量中拆解元组方法。
That’s how the tuple is unpacked in individual variables.
在上例中,赋值运算符左侧的变量数等于元组中的项数。如果数量不相等怎么办?
In the above example, the number of variables on the left of assignment operator is equal to the items in the tuple. What if the number is not equal to the items?
ValueError While Unpacking a Tuple
如果变量数多于或少于元组的长度,Python 会引发 ValueError。
If the number of variables is more or less than the length of tuple, Python raises a ValueError.
Unpack Tuple Items Using Asterisk (*)
在这种情况下,将“ " symbol is used for unpacking. Prefix " ”变为“y”,如下所示 −
In such a case, the "" symbol is used for unpacking. Prefix "" to "y", as shown below −
Example 1
tup1 = (10,20,30)
x, *y = tup1
print ("x: ", "y: ", y)
它将生成以下 output −
It will produce the following output −
x: y: [20, 30]
元组中的第一个值被分配给“x”,其余的项分配给了变为列表的“y”。
The first value in tuple is assigned to "x", and rest of items to "y" which becomes a list.
Example 2
在本例中,元组包含 6 个值,待拆包的变量有 3 个。我们在第二个变量前加上“*”。
In this example, the tuple contains 6 values and variables to be unpacked are 3. We prefix "*" to the second variable.
tup1 = (10,20,30, 40, 50, 60)
x, *y, z = tup1
print ("x: ",x, "y: ", y, "z: ", z)
它将生成以下 output −
It will produce the following output −
x: 10 y: [20, 30, 40, 50] z: 60
在这里,值首先被拆包成“x”和“z”,然后其余的值作为列表分配给“y”。
Here, values are unpacked in "x" and "z" first, and then the rest of values are assigned to "y" as a list.
Example 3
如果我们在第一个变量中加上“*”会怎么样?
What if we add "*" to the first variable?
tup1 = (10,20,30, 40, 50, 60)
*x, y, z = tup1
print ("x: ",x, "y: ", y, "z: ", z)
它将生成以下 output −
It will produce the following output −
x: [10, 20, 30, 40] y: 50 z: 60
在此同样地,元组以这样的方式被拆包:各个变量首先获取值,剩下的值留给列表“x”。
Here again, the tuple is unpacked in such a way that individual variables take up the value first, leaving the remaining values to the list "x".