【问题标题】:Python nested list comprehension (accessing nested elements) [duplicate]Python嵌套列表理解(访问嵌套元素)[重复]
【发布时间】:2017-11-08 09:16:31
【问题描述】:

我无法理解这里的语法。

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

【问题讨论】:

  • 被列为重复的问题是关于嵌套列表推导的,这个问题与此无关。

标签: python multidimensional-array nested list-comprehension


【解决方案1】:

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

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

您基本上是在打开列表中的各个项目并选择其中一项。

【讨论】:

  • 这看起来如何作为 matrix_b 的列表理解?
  • matrix_b的情况也是一样的,但是你会解压三个vars[a for a,b,c in matrix_b]
  • 好的,我现在看到了。我将其作为两个单独的语句a for a,b in matrix_a 阅读。哇,感谢您澄清:D 你们太棒了。
【解决方案2】:

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

查看截图

【讨论】:

  • 您可以复制文本而不是使用图像。此外,这似乎不是一个 answer ..?
【解决方案3】:

这样理解就行了:

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

如果有什么不清楚的地方请告诉我。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2021-07-09
    • 1970-01-01
    相关资源
    最近更新 更多