snowdream的Python推导式应用
a=[1,2,3,4,5,6,7,8,9]与a=[[1,2,3],[4,5,6],[7,8,9]]的转化
解法一:
a=[[1,2,3],[4,5,6],[7,8,9]]
a2=[j for i in a for j in i ]
b=[]
b1=[]
count=0
for i in a2:
b.append(i)
count+=1
if count==3:
b1.append(b)
count=0
b=[]
print(b1)
结果:
解法二:
a=[i for i in range(1,10)]
b=[[i for i in range(1,10)][j:j+3] for j in range(0,len(a),3)]
b=[a[j:j+3] for j in range(0,len(a),3)]
print(b)
结果:
解法三:
a=[[3*i+j+1 for j in range(3)]for i in range(3)]
print(a)