Python嵌套列表理解(访问嵌套元素)

时间:2017-11-08 09:16:32

标签: python multidimensional-array nested list-comprehension

我在这里理解语法有困难。

matrix_a = [[1, 2], [3, 4], [5, 6]]
matrix_b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[a for a, b in matrix_a]

输出:[1, 3, 5]

[a for b, a in matrix_a] 

输出:[2, 4, 6]

我对list-comprehensions的工作原理有所了解,但在访问嵌套列表中的某些元素时,我不理解语法。

我无法绕过这种语法。这个语法是如何工作的?逗号代表什么? a for a是什么意思?你能解释一下在幕后发生的事吗?最后,您将如何使用matrix_b

执行此操作

3 个答案:

答案 0 :(得分:2)

如果将其转换为for循环,可能更容易看到..?

res = []
for item in matrix_a:
    a, b = item   # a = item[0]; b = item[1]
    res.append(a)

您基本上解开了列表中的各个项目并选择了其中一个项目。

答案 1 :(得分:0)

我认为你在编写输出时有误 [a for a,b in matrix_a]返回[1 2 4],这是逻辑的,返回每个嵌套列表项的第一个元素

请参阅Output屏幕截图

答案 2 :(得分:0)

以这种方式理解:

[a for b, a in matrix_a]  #as
[a for [a, b] in matrix_a] #or
[a for (a, b) in matrix_a]
#matrix_a has elements as list of length 2 each
#so your list comprehenssion says, give me a output list -- having first element'a' from each element of matrix_a(whose each element represented as [a,b] type, with comma, becomes tuple (a,b)),
# then from [b,a] give me a, that is 2nd element
# and it will fail if you apply same on matrix_b, cause each element of matrix_b is not of type [a,b] i:e of length 2
# you will get "ValueError: too many values to unpack"

如果有什么不清楚,请告诉我。感谢。