无法理解具有两个循环的列表理解

2024-09-24 22:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

对我来说,解决这个问题(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]
        

enter image description here

为什么会出现这个错误?同样,这也不起作用

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

Tags: inimageselfforreturndef错误bit
1条回答
网友
1楼 · 发布于 2024-09-24 22:18:50

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

相关问题 更多 >