Python nested list comprehension (accessing nested elements)
本问题已经有最佳答案,请猛点这里访问。
我很难理解这里的语法。
1 2 3 4 | 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 | [a for b, a in matrix_a] |
号
输出:
我对列表理解的工作原理有一点了解,但在访问嵌套列表中的某些元素时,我不理解语法。
我就是不能用这种句法来概括。这个语法是如何工作的?逗号代表什么?
如果您将其转换为for循环,可能更容易看到….
1 2 3 4 | res = [] for item in matrix_a: a, b = item # a = item[0]; b = item[1] res.append(a) |
您基本上是打开列表中各个项目的包装,然后选择其中一个项目。
就这样理解:
1 2 3 4 5 6 7 8 | [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" |
号
如果有任何不清楚的地方请告诉我。谢谢。
我想你在这里写输出的时候弄错了[a for a,b in matrix_a]返回[1 2 4]这是逻辑的,返回每个嵌套列表项的第一个元素
参见屏幕截图