Write less to achieve more.

追求極簡是優秀程式員的特質之一,簡潔的代碼,不僅看起來更專業,可讀性更強,而且減少了出錯的幾率,
本文盤點一些Python中常用的一行(不限于一行)代碼,可直接用在日常編碼實踐中,
歡迎補充交流!
1. If-Else 三元運算子(ternary operator)
#<on True> if <Condition> else <on False>
print("Yay") if isReady else print("Nope")
2. 交換(swap)兩個變數值
a, b = b, a
3. 匿名函式(Lambda)過濾串列
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> list(filter(lambda x : x % 2 == 0 , numbers))
4. 模擬丟硬幣(Simulate Coin Toss)
使用random模塊的choice方法,隨機挑選一個串列中的元素
>>> import random
>>> random.choice(['Head',"Tail"])
Head
5. 讀取檔案內容到一個串列
>>> data = https://www.cnblogs.com/jiaoran/archive/2022/04/21/[line.strip() for line in open("file.txt")]
6. 最簡潔的斐波那契數列實作
fib = lambda x: x if x <= 1 else fib(x - 1) + fib(x - 2)
7. 字串轉換成位元組
"convert string".encode()
# b'convert string'
8. 反轉(Reverse)一個串列
numbers[::-1]
9. 串列推導式(List comprehension)
even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]
10. print陳述句將字串寫入檔案
挺方便,類似于linux中的 echo string > file
print("Hello, World!", file=open('file.txt', 'w'))
11. 合并兩個字典
dict1.update(dict2)
12. 按字典中的value值進行排序
dict = {'a':24, 'g': 52, 'i':12, 'k':33}
#reverse決定順序還是倒序
sorted(dict.items(), key = lambda x:x[1], reverse=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/460780.html
標籤:其他
下一篇:Day10
