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

二维 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]
发布了76 篇原创文章 · 获赞 221 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/chichu261/article/details/102847030