每次寫 Python 都會忘記該怎麼寫,最後只能去 Stack Overflow 查?我也一樣。時間一長,這讓人厭倦。
這 15 個 Python 技巧和竅門,可以幫你提高效率。
1. 交換值
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
2. 字符串列表合併爲一個字符串
sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)
print(sentence_string)
3. 將字符串拆分爲子字符串列表
sentence_string = "my name is George"
sentence_string.split()
print(sentence_string)
4. 通過數字填充初始化列表
[0]*1000 # List of 1000 zeros
[8.2]*1000 # List of 1000 8.2's
5. 字典合併