在Python中反转二维列表(矩阵)与`zip`函数的使用
2023-06-13 09:18:30 时间
之前刷 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]])
相关文章
- python字符串转化列表_Python列表到字符串的转换[通俗易懂]
- python 字符串转列表,列表转字符串
- python的进制转换器,Python进制转换[通俗易懂]
- python 多线程测试_【Python】多线程网站死链检测工具
- 可迭代对象 python_列表是可迭代对象吗
- 【说站】python系统内置方法如何获取
- 【说站】python scrapy处理翻页的方法
- Python udp编程_python socket udp
- 盘点一个Python列表处理的基础问题
- python(五)
- Python json中一直搞不清的load、loads、dump、dumps、eval
- opencv(4.5.3)-python(二十五)--二维直方图
- Python基础语法-函数-迭代器
- python-Python与SQLite数据库-SQLite数据库的基本知识(一)
- Python版本区别,Python 3和Python 2区别详解
- 小白的Python之路 day5 python模块详解及import本质编程语言
- python基础详解编程语言
- Python生成器、迭代器、可迭代对象详解编程语言
- Linux下如何快速卸载Python环境(linux如何卸载python)
- python-str字符串详解编程语言
- Linux 启动 Python编程之旅(linux打开python)
- 提升Linux环境:升级Python(linux升级python)
- Connecting to MSSQL with Python: A Comprehensive Guide for Beginners(python连接mssql)
- Linux下的Python开发技术之旅(linux下python开发)
- 用python实现的可以拷贝或剪切一个文件列表中的所有文件
- python列表与元组详解实例
- Python中列表(list)操作方法汇总