列表推导式
概念:提供了一种创建列表的简单快速的途径
(1) 一般形式
myList = [x for x in range(10)]
?
#分解后
myList = []
for x in range(10):
myList.append(x)
print(myList)
(2) 一般形式+判断
myList = [x for x in range(1,21) if x>10]
myList = [x for x in range(1,21) if x%2==0 and x<10]
(3) 生成列表嵌套
#第三种 生成列表嵌套
myList = [[x,x+1,x+2] for x in range(10)]
print(myList)
(4) 循环嵌套
#第四种 循环嵌套
myList = [x for x in range(3) for y in range(10)]
myList = [[x,y] for x in range(3) for y in range(10)]
3*4矩阵列表
myList = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
变成4*3矩阵列表
newList = [[v[i] for v in myList] for i in range(4)]
拆分
newList = []
for i in range(4):
appendList = []
for v in myList:
# print(v[i])
appendList.append(v[i])
newList.append(appendList)
print(newList)
(5) 字典推导式
Dict = {k:v for k,v in [(‘a‘,‘a‘),(‘b‘,‘b‘)]}
print(Dict)
原文地址:https://www.cnblogs.com/gugubeng/p/9715296.html
时间: 2024-11-06 22:01:33