English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The problem solved
Elements in an array (list) or tuple need to be exported to N variables.
The solution
Any sequence can be assigned to corresponding variables by simple variable assignment, the only requirement is that the number and structure of the variables must be consistent with the structure of 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)
Such operations are not limited to tuples and arrays, and they can also be used in strings. Unpacking supports most common sequences we often use, such as file iteration, various generators, etc.
s = 'Hello' a,b,c,d,e = s # a = 'H' # b = 'e'
If you want to discard some elements during the export process, Python does not support such syntax, but you can specify some rarely used variables to achieve your purpose.
data = ['google', 100.1, (2016, 5, 31] name, _, (_,month,_) = data # name = 'google' # month = '5' # other fields will be discarded
Summary
That's all for this article. I hope the content of this article can be helpful to everyone's learning or work. If you have any questions, you can leave a message for communication. Thank you for your support of the Shouting Tutorial.