1. 程式人生 > >Python 將多維資料轉為一維陣列 (總結)

Python 將多維資料轉為一維陣列 (總結)

import operator
from functools import reduce
a = [[1,2,3], [4,6], [7,8,9,8]]
print(reduce(operator.add, a))
[1, 2, 3, 4, 6, 7, 8, 9, 8]
a = [[1,2,3], [5, 8], [7,8,9]]
l=[]
for m in range(0,3):
    for i in a[m]:
        l.append(i)
print(l)
[1, 2, 3, 5, 8, 7, 8, 9]

from itertools import chain
b=[[1,2,3], [5,8], [7,8,9]]
c=list(chain(*b))
print(c)
[1, 2, 3, 5, 8, 7, 8, 9]
a=[[1,2,3], [5,8], [7,8,9]]
a= eval('['+str(a).replace(' ','').replace('[','').replace(']','')+']')
print(a)
[1, 2, 3, 5, 8, 7, 8, 9]

def flatten(a):
    if not isinstance(a, (list, )):
        return [a]
    else:
        b = []
        for item in a:
            b += flatten(item)
    return b
if __name__ == '__main__':
    a = [[[1,2],3],[4,[5,6]],[7,8,9]]
    print(flatten(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

ab = [[1,2,3], [5,8], [7,8,9]]
print([i for item in ab for i in item])
[1, 2, 3, 5, 8, 7, 8, 9]