【问题标题】:Unable to comprehend a list comprehension with two loops无法理解具有两个循环的列表理解
【发布时间】:2021-10-19 20:10:03
【问题描述】:

对我来说解决这个问题的解决方案 (https://leetcode.com/problems/flipping-an-image/) 是

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        return [[bit ^ 1 for bit in reversed(row)] for row in image]

但是,我觉得我在这里不了解列表理解,以下给了我一个错误:

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        return [[bit ^ 1] for bit in reversed(row) for row in image]
        

为什么我会收到这个错误?同样,这也不起作用。

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        return [bit ^ 1 for bit in reversed(row) for row in image]
        

【问题讨论】:

标签: python list-comprehension


【解决方案1】:

检查[Python.Docs]: Data Structures - Nested List Comprehensions,它包含一个类似于你的例子。

关于推导式评估需要记住的规则(它们可以无限扩展):

  1. 嵌套:从外到内
  2. 平原:从左到右
>>> l0 = [[1, 2, 3], [4, 5, 6]]
>>> 
>>> [[i ** 2 for i in l1] for l1 in l0]  # Nested
[[1, 4, 9], [16, 25, 36]]
>>> 
>>> [[i ** 2] for l1 in l0 for i in l1]  # Plain (notice the (reversed) for order)
[[1], [4], [9], [16], [25], [36]]

在上面的例子中:

  • 嵌套:外部范围内的标识符在内部范围内可见:l1
  • 普通:标识符必须在被引用之前存在:l1i之前

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2022-11-07
    • 2019-12-04
    • 2013-10-12
    相关资源
    最近更新 更多