1. 程式人生 > >python 基礎(六)

python 基礎(六)

矩陣 com ive variable comm end focus 基礎 lock

列表推導式

概念:提供了一種創建列表的簡單快速的途徑

(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)

python 基礎(六)