【发布时间】: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]
【问题讨论】:
-
尝试 2 和 3 需要翻转
for循环:[bit ^ 1 for row in image for bit in reversed(row)]并且行为会有所不同,将 2d 列表展平。版本 2 没有多大意义,你会得到一个 1 元素子列表的列表。请看Why not upload images of code/errors when asking a question? -
This thread 对带有多个 for 循环的列表推导有一些很好的解释。