随机生成二维列表:

import random
random.seed(123)
a=[[random.randint(0,10) for j in range(random.randint(3,6))] for i in range(random.randint(3,6))]
print('a =',a)

结果如下:

a = [[1, 6, 4, 1, 0], [8, 8, 5, 5, 0, 2], [5, 8, 5, 3]]

以下方法大多来源于网上,并有少许增补

1.方法一

a1=sum(a,[])
print('a1 =',a1)

2.方法二

a2=[j for i in a for j in i]
print('a2 =',a2)

3.方法三

a3=[]
[a3.extend(i) for i in a]
print('a3 =',a3)

4.方法四

import itertools
a4=list(itertools.chain(*a))
print('a4 =',a4)

5.方法五

import itertools
a5=list(itertools.chain.from_iterable(a))
print('a5 =',a5)

6.方法六

import functools
import operator
a6=functools.reduce(operator.concat,a)
print('a6 =',a6)

7.方法七

import functools
import operator
a7=functools.reduce(operator.iconcat,a,[])
print('a7 =',a7)

8.方法八

import functools
import operator
a8=functools.reduce(operator.add, a)
print('a8 =',a8)

9.方法九

import functools
a9=functools.reduce(lambda x,y:x+y,a)
print('a9 =',a9)

⒑方法十

import numpy as np
a10=list(np.concatenate(a))
print('a10 =',a10)

⒒方法十一

import tkinter as tk
a11=list(tk._flatten(a))
print('a11 =',a11)

⒓方法十二

a12=[]
for i in a:
    a12+=i 
print('a12 =',a12)

⒔方法十三

i=0
a13=[]
while i<len(a):
    a13+=a[i]
    i+=1
print('a13 =',a13)

⒕方法十四

a14=[]
def fun14(a14,i=0):
    if i<len(a):
        a14+=a[i]
        return fun14(a14,i+1)
fun14(a14)
print('a14 =',a14)

⒖方法十五

a15=[int(i) for i in str(a).replace('[','').replace(']','').split(',')]
print('a15 =',a15)

综上结果如下:

a = [[1, 6, 4, 1, 0], [8, 8, 5, 5, 0, 2], [5, 8, 5, 3]] #原二维列表
a1 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a2 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a3 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a4 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a5 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a6 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a7 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a8 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a9 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a10 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a11 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a12 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a13 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a14 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
a15 = [1, 6, 4, 1, 0, 8, 8, 5, 5, 0, 2, 5, 8, 5, 3]
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐