Lack of understanding of Python multi-variant assignments

I am new to Python (with Java base). I read Dive Into Python in chapter 3, which I found about Multi-Variable Assignment. Perhaps some of you can help me understand what is going on in this code below:

>>> params = {1:'a', 2:'b', 3:'c'}
>>> params.items() # To display list of tuples of the form (key, value).
[(1, 'a'), (2, 'b'), (3, 'c')]

>>> [a for b, a in params.items()] #1
['a', 'b', 'c']
>>> [a for a, a in params.items()] #2
['a', 'b', 'c']
>>> [a for a, b in params.items()] #3
[ 1 ,  2 ,  3 ]
>>> [a for b, b in params.items()] #4
[ 3 ,  3 ,  3 ]

Until now, I understand that #1they #2have the same output, displaying the values ​​of the tuple. #3displays the tuple key, but #4simply displays the last key from the list of tuples.

I do not understand the use of the variable aand variable bfor each case above:

  • a for b, a ... → display values
  • a for a, a ... → display values
  • a for a, b ... → display keys
  • a for b, b ... → display the last key

Can someone design a loop thread for each case above?

+5
3

, , :

[a for b, a in params.items()]

result = []
for item in params.items():
    b = item[0]
    a = item[1]
    result.append(a)

[a for a, a in params.items()]

result = []
for item in params.items():
    a = item[0]
    a = item[1] # overwrites previous value of a, hence this yields values, 
                # not keys
    result.append(a)

[a for a, b in params.items()]

result = []
for item in params.items():
    a = item[0]
    b = item[1]
    result.append(a)

[a for b, b in params.items()]

result = []
for item in params.items():
    b = item[0]
    b = item[1]
    result.append(a) # note use of a here, which was not assigned

. , a , , , 3. , .

+8

. - () Python 2.x; , , LC. 3.x.

>>> [x for x in (1, 2, 3)]
[1, 2, 3]
>>> x
3

3>> [x for x in (1, 2, 3)]
[1, 2, 3]
3>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
+6

- .

params.items()

.

, , , :

>>> a, b = (2, 3)
>>> a
2
>>> b
3

.

>>> [a for a, b in [(2, 3), (4, 5)]]
[2, 4]

a . # 1 , .

>>> [b for a, b in [(2, 3), (4, 5)]]
[3, 5]

. # 3.

. # 2

>>> [a for a, a in [(2, 3), (4, 5)]]
[3, 5]
>>> a,a = (2,3)
>>> a
3

, . .

№4 . , , .

>>> [a for b, b in [(2, 3), (4, 5)]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

, .

+3

All Articles