最近看了別人的code寫得很精簡

其中有一個寫法看不是很懂,只知道將python寫得很簡潔,於是查了一下,寫成心得

第一個範例:在mylist內有許多數字,找出數值等於0的位置

mylist=[0,1,2,4,0,2,3,4,6,8,0]
result=[col for col in range(len(mylist)) if mylist[col]==0]
print(result)

其原意如下

mylist=[0,1,2,4,0,2,3,4,6,8,0]
result=[]
for col in range(len(mylist)):
    if mylist[col]==0:
        result.append(col)
print(result)

上述這兩個的結果都是一樣的

[0,4,10]

第二個範例:在x, y 內有許多數字,找出偶數並讓他們相加,結果應該會是2+6 , 4+6, 2+8, 4+8

x=[1,2,3,4]

y=[5,6,7,8]

z= [ a+b for a in x  for b in y if a%2==0 and b%2==0]
print("z = {}".format(z))

其原意如下

result=[]
for i in x:
    for j in y:
        if i%2==0:
            if j%2==0:
                result.append(i+j)
print(result)

上述這兩個的結果都是一樣的

[8,10,10,12]
創作者介紹
創作者 YiChung's space 的頭像
Cheng yichung

YiChung's space

Cheng yichung 發表在 痞客邦 留言(0) 人氣( 4 )