Use Python to export elements of an array into a variable (unpacking)

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.