首页后端开发Python在Python中反转二维列表(矩阵)与`zip`函数的使用

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

时间2023-04-23 07:54:01发布访客分类Python浏览326
导读:之前刷 LeetCode 题目的时候,偶尔会需要反转二维列表,这里总结了几种 Python 实现。循环简单的二维循环,将原始二维列表的每一行的第 N 个元素,放到新的二维列表的第 N 行中。def invert_matrix(matrix:...

之前刷 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]])

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

pythonzip函数效率语法

若转载请注明出处: 在Python中反转二维列表(矩阵)与`zip`函数的使用
本文地址: https://pptw.com/jishu/6115.html
【使用Python实现算法】01 语言特性 语义化版本与其在Python中的使用

游客 回复需填写必要信息