Python 二维 list列表 转置转换 二维转一维 数组

mac2024-10-29  15

二维 List列表转换(转置)

方法一 zip()

def test(): a = [[1, 2, 3], [4, 5, 6]] b = tuple(zip(*a)) c = list(zip(*a)) d = list(map(list, zip(*a))) print(b) # ((1, 4), (2, 5), (3, 6)) print(c) # [(1, 4), (2, 5), (3, 6)] print(d) # [[1, 4], [2, 5], [3, 6]]

方法二 numpy

pass

二维List转一维

def test(): a = [[1, 2, 3], [4, 5, 6]] b = [i for item in a for i in item] print(b) def test(): from functools import reduce a = [[1, 2, 3], [4, 5, 6]] b = reduce(lambda x, y: x + y, a) print(b) # [1, 2, 3, 4, 5, 6] def test(): from itertools import chain a = [[1, 2, 3], [4, 5, 6]] b = list(chain.from_iterable(a)) print(b) # [1, 2, 3, 4, 5, 6] def test(): from tkinter import _flatten a = [[1, 2, 3], [4, 5, 6]] b = list(_flatten(a)) print(b) # [1, 2, 3, 4, 5, 6]
最新回复(0)