OneLiner 解释 - Python

OneLiner explanation - Python

我在 LeetCode 中有一个任务叫做 832。翻转图像

Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed.

For example, flipping [1,1,0] horizontally results in [0,1,1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

For example, inverting [0,1,1] results in [1,0,0].

Example 1:

Input: image = [[1,1,0],[1,0,1],[0,0,0]]

Output:[[1,0,0],[0,1,0],[1,1,1]]

Explanation:

First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image:[[1,0,0],[0,1,0],[1,1,1]]

有人提供的解决方案是Python中的一行:

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

并且调试一行代码根本没有效果所以我的请求是逐个解释代码。大多数情况下,我在 for 循环 之前的那些部分有问题,因为我在互联网上找不到可以在循环之前放置代码的解释。

class Solution:

定义 Class 解决方案

def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:

定义 flipAndInvertImage 函数,带有一个整数列表列表的参数,以及相同类型的输出。

好的,现在单线:

return [[1 ^ i for i in reversed(row)] for row in image]

这称为生成器表达式,其中在

a = [int(i) for i in list_of_strings]

例如,您循环遍历 list_of_strings,然后对其应用函数 int()。大致类似于这样做:

a = []
for i in list_of_strings:
    a.append(int(i))

因此 [[...] for row in image] 是第一个生成器表达式,并使变量 row 遍历图像数组中的行。

[1 ^ i for i in reversed(row)] 是 second/inner 生成器。它循环遍历外部生成器给出的变量行,使用 reverse() 函数将其反转,然后对其应用二进制 x-or 运算。 1 ^ i 所做的就是把 1 变成 0,然后把 0 变成 1。