将多维列表转化为一维
Posted ~小疯子~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将多维列表转化为一维相关的知识,希望对你有一定的参考价值。
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]
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]
以上是关于将多维列表转化为一维的主要内容,如果未能解决你的问题,请参考以下文章
reduce实现计算数组中每个元素出现的次数 数组去重 将多维数组转化为一维