之前刷 LeetCode 题目的时候,偶尔会需要反转二维列表,这里总结了几种 Python 实现。
循环
简单的二维循环,将原始二维列表的每一行的第 N 个元素,放到新的二维列表的第 N 行中。
1 | def invert_matrix(matrix: list[list[int]]) -> list[list[int]]: |
列表推导式
本质上和循环算法是相同的,使用列表推导式语法来实现。
1 | def invert_matrix(matrix: list[list[int]]) -> list[list[int]]: |
使用zip
函数
Python 内置函数zip
,可以不断迭代多个列表相同索引的元素组成的元组。
Init signature: zip(self, /, *args, **kwargs)
Docstring:
zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.
>>> list(zip('abcdefg', range(3), range(4)))
[('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
The zip object yields n-length tuples, where n is the number of iterables
passed as positional arguments to zip(). The i-th element in every tuple
comes from the i-th iterable argument to zip(). This continues until the
shortest argument is exhausted.
If strict is true and one of the arguments is exhausted before the others,
raise a ValueError.
Type: type
Subclasses:
zip
函数的一个常见用法是提取一个无限长度的生成器的前 N 个元素。
1 | def gen_fib() -> Generator[int, None, None]: |
另外一个我喜欢的zip
函数的用法是将两个列表组合为一个字典。
1 | assert dict(zip('abcde', range(5))) == {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} |
使用zip
函数来反转二维列表也很简单。
1 | def invert_matrix(matrix: list[list[int]]) -> list[list[int]]: |
使用numpy
库
上述的三种方法受限于 Python 解释器,效率不是非常高。
如果要进行专业的数值分析和计算的话,可以使用numpy
库的matrix.transpose
方法来翻转矩阵。
1 | import numpy as np |