Detail python unpacking iterative data such as tuple list
- 2020-06-19 11:00:36
- OfStack
Unpacking is the splitting of data in a structure into separate variables.
Take tuples as an example:
>>> a = ('windows', 10, 25.1, (2017, 12, 29))
Suppose the data means buying 10 copies of windows, each worth $25.1. The data was acquired on December 29, 2017.
We need to get the price per copy of this data:
>>> a[2]
Unpacking can also be used:
>>>os_type, number, price, dat = a
>>>price
Note that unpacking objects must be iteratable such as tuple and list.
Question 2: We only care about price and date, not system and quantity:
Use an unused variable and then match the first two terms with the adaptation symbol *.
>>> *_, price, dat = a
>>> price
>>>dat
Third, if we only care about the price and the month, how do we unlock the bag?
>>> *_, price, (_, m, d) = a
>>> price
>>> m
Note that unpacking is supported in python, but started in python3 with * to match multiple values. So pay attention to the python version information when using *.
Question: If the left and right Numbers do not match and * is not used, what will the result be?
ValueError: too many values to unpack
>>> _, price, (*_, m, d) =a
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
_, price, (*_, m, d) =a
ValueError: too many values to unpack (expected 3)
conclusion