常用Python簡潔代碼片段

Write less to achieve more.
用盡可能的少的代碼實現複雜功能。

本文介紹一些實用的代碼簡潔小技巧,讓你的代碼看起來更專業,可讀性更強。

1. 單行 If-Else

isReady = False

# A regular if-else
if isReady:
    print("Yay")
else:
    print("Nope")
    
# A neat little shorthand
print("Yay") if isReady else print("Nope")

2. 交換(swap)兩個變量值,不使用臨時變量

a = 1
b = 2

a, b = b, a

# Now a = 2 and b = 1

3. 鏈式比較(Chain Comparisons)

# regular one
x > 0 and x < 200

# neat
0 < x < 200

4. 匿名函數(Lambda Expressions)

>>> numbers = [1, 2, 3, 4, 5, 6]
>>> list(filter(lambda x : x % 2 == 0 , numbers))
[2, 4, 6]

5. 模擬丟硬幣(Simulate Coin Toss)

使用random模塊的choice方法,隨機挑選一個列表中的元素

>>> import random
>>> random.choice(['Head',"Tail"])
Head
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章