Black & Python practical - unpacking elements (1)

Demand:
Many times already have on hand a list or tuple has n elements, these elements are you going to get singled out (unpacked) into a set consisting of n variables (and here's a collection of Python different set their own )in.

Methods:
Obviously, the best way is to do it with a direct assignment (=), the only caveat is that the number of variables must be new and original list, the same number of elements inside the tuple:

In [1]: p = (4, 6, 7)
In [2]: x, y, z = p
In [3]: x
Out[3]: 4
In [4]: y
Out[4]: 6
In [5]: z
Out[5]: 7

The In [. 7]: Data = [ 'Jason', 2010, 59, ( 'SE', 'the Web', 'the Java')]
the In [. 8]: name, graduate_year, weight, (Job, Content, Language) = Data
the in [. 9]: name
Out [. 9]: 'Jason'
the in [10]: Job
Out [10]: 'SE'
the in [. 11]: Language
Out [. 11]: 'the Java'
It should be noted that, if a the number does not match, you will naturally get a bug report:

The In [12 is]: Mine = (2,. 3,. 4)
the In [13 is]: X, Y = Mine
-------------------------- -------------------------------------------------
ValueError traceback (Last Call Recent MOST)
<-13 is IPython-INPUT-be106769942b> in <Module1> ()
---->. 1 X, Y = Mine
a ValueError: TOO MANY values to the unpack (expected 2)

extension:
the above-described method of unpacking iterative actually applies to all variable data, in addition to the list of tuples, naturally also be used in the above string, file, like an iterator. E.g:

The In [14]: S = 'Jason'
the In [15]: A, B, C, D, E = S
the In [16]: A
Out [16]: 'J'
the In [. 17]: C
Out [. 17] : 'S'
the in [18 is]: E
Out [18 is]: 'n-'

of course, you can give up some unwanted elements, here, Python is not specified setting a discard symbol, you are free to use their own like symbols, such as:

The In [. 19]: Data = [ 'Qin', 'F', 'Chengdu', '6000']
the In [20 is]: name, _, _, Money = Data
the In [21 is]: name
Out [21 is]: ' Qin '
the in [22 is]: Money
Out [22 is]:' 6000 '
here' _ 'variable is to be discarded.
Taken as a whole, the techniques described in this major is more convenient to allow users to quickly get to the desired value, and stored in a new variable. For these classes iterator variable data is concerned, generally we like to use the index to take corresponding element, but always with a subscript do the operation, may not be easy, so the selection of variables to obtain timely, sometimes easier .

Guess you like

Origin www.cnblogs.com/valorchang/p/11289131.html