Home >Backend Development >Python Tutorial >Export elements of an array into variables using Python (unpacking)
Below I will share with you an article using Python to export the elements of an array into variables (unpacking). It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
I recently encountered a problem at work. I need to use Python to export the elements in an array (list) or tuple (tuple) to N variables. Now I will share the method I implemented. For everyone, friends in need can refer to it. Let’s take a look below.
Solved problem
Needs to export the elements in an array (list) or tuple (tuple) to N variables.
Solution
Any sequence can assign its elements to the corresponding variables through simple variable assignment. The only requirement is that the number and structure of the variables need to be exactly the same as the structure in the sequence.
p = (1, 2) x, y = p # x = 1 # y = 2 data = ['google', 100.1, (2016, 5, 31)] name, price, date = data # name = 'google' # price = 100.1 # date = (2016, 5, 31) name, price, (year, month, day) = data # name = 'google' # price = 100.1 # year = 2016 # month = 5 # day = 31
If the variable structure and element structure are inconsistent, you will encounter the following error:
p = (1, 2) x, y, z = p Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> x, y, z = p ValueError: not enough values to unpack (expected 3, got 2)
In fact, such operations are not limited to tuples and arrays, but can also be used in strings. Unpacking supports most of our common sequences, such as file iteration, various generators, etc.
s = 'Hello' a,b,c,d,e = s # a = 'H' # b = 'e'
If you want to lose some elements during the export process, Python does not actually support such syntax, but you can specify some uncommon variables to achieve your goal the goal of.
data = ['google', 100.1, (2016, 5, 31)] name, _, (_,month,_) = data # name = 'google' # month = '5' # other fileds will be discarded
The above is the detailed content of Export elements of an array into variables using Python (unpacking). For more information, please follow other related articles on the PHP Chinese website!