在Python中反转二维列表(矩阵)与`zip`函数的使用

您所在的位置:网站首页 python分类函数 在Python中反转二维列表(矩阵)与`zip`函数的使用

在Python中反转二维列表(矩阵)与`zip`函数的使用

2023-04-21 18:01| 来源: 网络整理| 查看: 265

之前刷 LeetCode 题目的时候,偶尔会需要反转二维列表,这里总结了几种 Python 实现。

循环

简单的二维循环,将原始二维列表的每一行的第 N 个元素,放到新的二维列表的第 N 行中。

def invert_matrix(matrix: list[list[int]]) -> list[list[int]]: new_matrix = [] for i in range(len(matrix[0])): new_row = [] for row in matrix: new_row.append(row[i]) new_matrix.append(new_row) return new_matrix列表推导式

本质上和循环算法是相同的,使用列表推导式语法来实现。

def invert_matrix(matrix: list[list[int]]) -> list[list[int]]: return [[row[i] for row in matrix] for i in range(len(matrix[0]))]使用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 个元素。

def gen_fib() -> Generator[int, None, None]: a, b = 1, 1 while True: yield a a, b = b, a + b assert [num for _, num in zip(range(5), gen_fib())] == [1, 1, 2, 3, 5]

另外一个我喜欢的zip函数的用法是将两个列表组合为一个字典。

assert dict(zip('abcde', range(5))) == {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

使用zip函数来反转二维列表也很简单。

def invert_matrix(matrix: list[list[int]]) -> list[list[int]]: return [list(t) for t in zip(*matrix)]使用numpy库

上述的三种方法受限于 Python 解释器,效率不是非常高。 如果要进行专业的数值分析和计算的话,可以使用numpy库的matrix.transpose方法来翻转矩阵。

import numpy as np matrix = np.arange(9).reshape((3,3)) assert matrix.transpose() == np.array([[0, 3, 6], [1, 4, 7], [2, 5, 8]])


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3