5

我是 Python 新手(以 Java 为基础)。我阅读了Dive Into Python书籍,在第 3 章中找到了关于Multi-Variable Assignment. 也许你们中的一些人可以帮助我理解下面这段代码中发生的事情:

>>> 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 ]

到目前为止我所理解的是#1and#2具有相同的输出,显示元组的值。#3显示元组的键,#4只显示元组列表中的最后一个键。

我不明白上述每种情况下变量a和变量的用法:b

  1. a for b, a ...-> 显示值
  2. a for a, a ...-> 显示值
  3. a for a, b ...-> 显示键
  4. a for b, b ...-> 显示最后一个键

谁能详细说明上述每种情况的循环流程?

4

3 回答 3

8

您在那里使用的列表理解大致翻译如下:

[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. 如果你先执行这个语句,你会得到一个错误。

于 2012-08-03T08:07:42.393 回答
6

在所有四种情况下,元组中的名称都按顺序绑定到序列对中的每个元素。第四个实例是 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
于 2012-08-03T08:05:34.143 回答
3

元组只是将变量打包在一起。当你打电话时你会得到这些对

params.items()

正如您在评论中所写的那样。

要解压一个元组,你需要做的是:

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

使用列表推导时也是如此。

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

here a takes out the first element of the tuple for every tuple in the list. This is #1 in your case using the params list instead of my short list.

If you instead write

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

you get the second element. This corresponds to your #3.

The other two does not really make sense. In #2 you have

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

which just lets a be first the first and then directly overwrites it with the second argument in each unpacking. You can se this same thing happen with the single tuple.

Last #4 is simply wring. Had you not already used a as a variable this would not have worked since a then doesn't exist.

>>> [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

I hope this answers your questions.

于 2012-08-03T08:14:00.843 回答