def printlist(list):
for x in list:
print(x)
list=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
printlist(list)
print('-----------------')
list2=[[ y[x] for y in list ] for x in range(4)]#使用复杂推导式将数组转置
printlist(list2)
print('-----------------')
def changeList(list):#使用简单推导式
list2=[]
for x in range(4):
list2.append([y[x] for y in list])
return list2
list3=changeList(list)
printlist(list3)
print('-----------------')
def changeList2(list):#不使用推导式
list2=[]
for x in range(4):
list3=[]
for y in list:
list3.append(y[x])
list2.append(list3)
return list2
list4=changeList2(list)
printlist(list4)
打印如下:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
—————–
[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]
—————–
[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]
—————–
[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]
同时再说下推导式,可以有多重嵌套循环,每个循环可加一个if语句过滤,如下:
lst=[ x for x in range(100) if x%2==0]
print(lst)
lst2=[x+y for x in range(10) if x>5 for y in range(10) if y<5 ]
print(lst2)
打印如下:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
[6, 7, 8, 9, 10, 7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13]