Home >Backend Development >Python Tutorial >Export elements of an array into variables using Python (unpacking)

Export elements of an array into variables using Python (unpacking)

不言
不言Original
2018-04-27 15:32:392515browse

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 = &#39;Hello&#39;
a,b,c,d,e = s
# a = &#39;H&#39;
# b = &#39;e&#39;

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 = [&#39;google&#39;, 100.1, (2016, 5, 31)]
name, _, (_,month,_) = data
# name = &#39;google&#39;
# month = &#39;5&#39;
# 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn