Here's to share an article using Python to export the elements of an array into a variable (unpacking), it has a good reference value, I hope to help you. Come and see it together.
Recently encountered a problem in the work, you need to use the Python array (list) or tuple (tuple) elements in the export to n variables, now my implementation of the method to share to everyone, the need for friends can reference, the following to see together.
The problem solved
You need to export the elements in an array (list) or tuple (tuple) to n variables.
Solution to the solution
Any sequence can assign its elements to a corresponding variable by a simple variable assignment, the only requirement being that the number and structure of the variable are exactly the same as the structure in the sequence.
p = (1, 2) x, y = p# x = # y = 2data = [' Google ', 100.1, (5, +)]name, price, date = data# name = ' google ' # = 100.1# date = (5, +) name, Price, (year, month, day) = data# name = ' Google ' # price = 100.1# year = 2016# month = AA Day = 31
If the variable structure and element structure are inconsistent, you will encounter the following error:
p = (1, 2) x, y, z = ptraceback (most recent call last): File ' <pyshell#12> ', line 1, in <module> x, y, z = Pvalueerror:not enough values to unpack (expected 3, got 2)
In fact, such operations are not limited to tuples and arrays, and are also available in strings. Unpacking supports most of our common sequences, such as file iterations, various generators, and so on.
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 this syntax, but you can specify a few variables that are not commonly used to achieve your goal.
data = [' Google ', 100.1, (5, +)]name, _, (_,month,_) = data# name = ' google ' # month = ' 5 ' # other fileds would be dis Carded