前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >在Python中反转二维列表(矩阵)与`zip`函数的使用

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

作者头像
杜逸先
发布2023-04-13 16:24:47
发布2023-04-13 16:24:47
4K00
代码可运行
举报
运行总次数:0
代码可运行

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

循环

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

代码语言:javascript
代码运行次数:0
运行
复制
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

列表推导式

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

代码语言:javascript
代码运行次数:0
运行
复制
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,可以不断迭代多个列表相同索引的元素组成的元组。

代码语言:javascript
代码运行次数:0
运行
复制
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 个元素。

代码语言:javascript
代码运行次数:0
运行
复制
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函数的用法是将两个列表组合为一个字典。

代码语言:javascript
代码运行次数:0
运行
复制
assert dict(zip('abcde', range(5))) == {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

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

代码语言:javascript
代码运行次数:0
运行
复制
def invert_matrix(matrix: list[list[int]]) -> list[list[int]]:
    return [list(t) for t in zip(*matrix)]

使用numpy

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

代码语言:javascript
代码运行次数:0
运行
复制
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]])
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-102,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 循环
  • 列表推导式
  • 使用zip函数
  • 使用numpy库
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档