喝杯咖啡的功夫就能學(xué)會的100個非常有用的Python技巧
點擊上方“程序員大白”,選擇“星標(biāo)”公眾號
重磅干貨,第一時間送達
作者:Fatos Morina
編譯:ronghuaiyang
有些可能大家都了解,還有一些確實不太常見,但是確實好用,內(nèi)容有點多,100條,分3次發(fā),先發(fā)第1~33條。

Python現(xiàn)在非常流行,主要是因為它簡單,容易學(xué)習(xí)。你可以用它來完成很多任務(wù),比如數(shù)據(jù)科學(xué)和機器學(xué)習(xí)、web開發(fā)、腳本編寫、自動化等。
這里總結(jié)了100條很有用的tips給你:
1. “for” 循環(huán)中的“Else”條件
除了目前為止你已經(jīng)看到的所有Python代碼之外,你有可能錯過了下面的“for-else”,這也是我在幾周前第一次看到的。
這是一個用于循環(huán)遍歷列表的“for-else”方法,盡管對列表進行了迭代,但仍然有一個“else”條件,這是非常不尋常的。
這是我在Java、Ruby或JavaScript等其他編程語言中所沒有看到的。
讓我們看一個實踐中的例子。
假設(shè)我們要檢查列表中是否沒有奇數(shù)。
讓我們來遍歷一下:
numbers = [2, 4, 6, 8, 1]
for number in numbers:
if number % 2 == 1:
print(number)
break
else:
print("No odd numbers")
如果我們發(fā)現(xiàn)一個奇數(shù),那么這個數(shù)字將被打印,因為break將被執(zhí)行,而else分支將被跳過。
否則,如果break從未被執(zhí)行,執(zhí)行流將繼續(xù)執(zhí)行else分支。
在這個例子中,我們將輸出1。
2. 使用命名的變量從列表中取元素
my_list = [1, 2, 3, 4, 5]
one, two, three, four, five = my_list
3. 使用heapq從列表中獲取最大或最小的元素
import heapq
scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
print(heapq.nlargest(3, scores)) # [91, 87, 82]
print(heapq.nsmallest(5, scores)) # [15, 33, 33, 49, 51]
4. 把列表中的值作為參數(shù)傳遞給方法
可以使用" * "提取列表中的所有元素:
my_list = [1, 2, 3, 4]
print(my_list) # [1, 2, 3, 4]
print(*my_list) # 1 2 3 4
當(dāng)我們想將列表中的所有元素作為方法參數(shù)傳遞時,這很有用:
def sum_of_elements(*arg):
total = 0
for i in arg:
total += i
return total
result = sum_of_elements(*[1, 2, 3, 4])
print(result) # 10
5. 獲取列表的所有中間元素
_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]
print(elements_in_the_middle) # [2, 3, 4, 5, 6, 7]
6. 一行賦值多個變量
one, two, three, four = 1, 2, 3, 4
7. 列表推導(dǎo)
你可以使用推導(dǎo)如,讓我們將列表中的每個數(shù)字都取二次方:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers]
print(squared_numbers)
推導(dǎo)不僅僅局限于使用列表。還可以將它們與字典、集合和生成器一起使用。
讓我們看另一個例子,使用字典推導(dǎo)將一個字典的值提升到二階:

Comprehensions are not just limited to working with lists. You can also use them with dictionaries, sets, and generators as well.
dictionary = {'a': 4, 'b': 5}
squared_dictionary = {key: num * num for (key, num) in dictionary.items()}
print(squared_dictionary) # {'a': 16, 'b': 25}
8. 通過Enum枚舉相同概念的相關(guān)項
來自文檔:
Enum是綁定到唯一值的一組符號名。它們類似于全局變量,但它們提供了更有用的repr()、分組、類型安全和其他一些特性。
下面是例子:
from enum import Enum
class Status(Enum):
NO_STATUS = -1
NOT_STARTED = 0
IN_PROGRESS = 1
COMPLETED = 2
print(Status.IN_PROGRESS.name) # IN_PROGRESS
print(Status.COMPLETED.value) # 2
9. 不使用循環(huán)來重復(fù)字符串
name = "Banana"
print(name * 4) # BananaBananaBananaBanana
10. 像數(shù)學(xué)式子一樣比較3個數(shù)字
如果你有一個值,你想比較它是否在其他兩個值之間,有一個簡單的表達式,你在數(shù)學(xué)中使用:
1 < x < 10
這是我們在小學(xué)學(xué)過的代數(shù)表達式。但是,你也可以在Python中使用相同的表達式。
是的,你沒聽錯。之前,你可能已經(jīng)做過這種形式的比較:
1 < x and x < 10
現(xiàn)在,你只需要在Python中使用以下代碼:
1 < x < 10

這在Ruby中行不通,Ruby是一種旨在讓程序員開心的編程語言。這在JavaScript中也可以工作。
看到這樣一個簡單的表達沒有得到更廣泛的討論,我真的很驚訝。至少,我還沒有看到人們這么頻繁地提到它。
11. 在單條語句中合并字典
從Python 3.9開始可用:
first_dictionary = {'name': 'Fatos', 'location': 'Munich'}second_dictionary = {'name': 'Fatos', 'surname': 'Morina', 'location': 'Bavaria, Munich'}result = first_dictionary | second_dictionaryprint(result) # {'name': 'Fatos', 'location': 'Bavaria, Munich', 'surname': 'Morina'}
12. 在tuple中找到元素的索引
books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')print(books.index('Mastery')) # 3
13. 把字符串列表轉(zhuǎn)換成一個列表
假設(shè)你在一個字符串函數(shù)中獲得輸入,但它應(yīng)該是一個列表:
input = "[1,2,3]"
你不需要那種格式,你需要的是一個列表:
input = [1,2,3]
或者你可能從一個API調(diào)用得到以下響應(yīng):
input = [[1, 2, 3], [4, 5, 6]]
你所要做的就是導(dǎo)入模塊ast,然后調(diào)用它的方法literal_eval,而不用去寫復(fù)雜的正則表達式:
import astdef string_to_list(string): return ast.literal_eval(string)
這就是你需要做的。
現(xiàn)在你會得到一個列表作為結(jié)果,或者列表的列表,如下所示:
import ast
def string_to_list(string):
return ast.literal_eval(string)
string = "[[1, 2, 3],[4, 5, 6]]"
my_list = string_to_list(string)
print(my_list) # [[1, 2, 3], [4, 5, 6]]
14. 使用命名參數(shù)避免 “trivial” 錯誤
假設(shè)你想求兩個數(shù)的差。差不是可交換的:
a - b != b -a
然而,我們可能會忘記參數(shù)的順序,這可能會導(dǎo)致“trivial”錯誤:
def subtract(a, b):
return a - b
print((subtract(1, 3))) # -2
print((subtract(3, 1))) # 2
為了避免這種潛在的錯誤,我們可以簡單地使用命名參數(shù),參數(shù)的順序不再重要:
def subtract(a, b):
return a - b
print((subtract(a=1, b=3))) # -2
print((subtract(b=3, a=1))) # -2
15. 使用單個print()語句打印多個元素
print(1, 2, 3, "a", "z", "this is here", "here is something else")
16. 一行打印多個元素
print("Hello", end="")
print("World") # HelloWorld
print("Hello", end=" ")
print("World") # Hello World
print('words', 'with', 'commas', 'in', 'between', sep=', ')
# words, with, commas, in, between
17. 打印多個值,每個值之間使用自定義分隔符
你可以很容易地做高級打印:
print("29", "01", "2022", sep="/") # 29/01/2022
print("name", "domain.com", sep="@") # [email protected]
18. 不能在變量名的開頭使用數(shù)字
four_letters = “abcd” # this works4_letters = “abcd” # this doesn’t work
19. 不能在變量名的開頭使用操作符
+variable = “abcd” # this doesn’t work
20. 你不能把0作為數(shù)字的第一個數(shù)字
number = 0110 # this doesn't work
21. 你可以在變量名的任何位置使用下劃線字符
這意味著,在任何你想要的地方,在變量名中,你想要多少次就有多少次:
a______b = "abcd" # this works
_a_b_c_d = "abcd" # this also works
我不鼓勵你使用它,但如果你看到像這樣奇怪的變量命名,要知道它實際上是一個有效的變量名。
22. 可以用下劃線分隔較大的數(shù)字
這樣讀起來更容易。
print(1_000_000_000) # 1000000000
print(1_234_567) # 1234567
23. 顛倒列表的順序
my_list = ['a', 'b', 'c', 'd']
my_list.reverse()
print(my_list) # ['d', 'c', 'b', 'a']
24. 使用step函數(shù)對字符串切片
my_string = "This is just a sentence"
print(my_string[0:5]) # This
# Take three steps forward
print(my_string[0:10:3]) # Tsse
25. 反向切片
my_string = "This is just a sentence"
print(my_string[10:0:-1]) # suj si sih
# Take two steps forward
print(my_string[10:0:-2]) # sjs i
26. 只有開始或結(jié)束索引的部分切片
表示切片的開始和結(jié)束的索引可以是可選的。
my_string = "This is just a sentence"
print(my_string[4:]) # is just a sentence
print(my_string[:3]) # Thi
27. Floor 除法
print(3/2) # 1.5
print(3//2) # 1
28. == 和 “is” 的差別
" is "檢查兩個變量是否指向內(nèi)存中的同一個對象。
" == "比較這兩個對象的值是否相等。
first_list = [1, 2, 3]
second_list = [1, 2, 3]
# Is their actual value the same?
print(first_list == second_list) # True
# Are they pointing to the same object in memory
print(first_list is second_list)
# False, since they have same values, but in different objects in memory
third_list = first_list
print(third_list is first_list)
# True, since both point to the same object in memory
29. 更改分配給另一個變量的變量的值
當(dāng)一個變量被賦值給另一個變量時,它的值實際上被復(fù)制到第二個變量中。
這意味著第一個變量之后的任何變化都不會反映在第二個變量中:
first = "An initial value"
second = first
first = "An updated value"
print(first) # An updated value
print(second) # An initial value
30. 檢查一個字符串是否大于另一個字符串
first = "abc"
second = "def"
print(first < second) # True
second = "ab"
print(first < second) # False
31. 檢查字符串是不是從特定字符開始的
my_string = "abcdef"
print(my_string.startswith("b")) # False
32. 使用id()找到變量的唯一id
print(id(1)) # 4325776624
print(id(2)) # 4325776656
print(id("string")) # 4327978288
33. Integers, floats, strings, booleans, sets以及tuples是不可修改的
當(dāng)將變量賦給整數(shù)、浮點數(shù)、字符串、布爾值、集合和元組等不可變類型時,該變量將指向內(nèi)存中的對象。
如果給該變量賦了另一個值,原來的對象仍然在內(nèi)存中,但是指向它的變量丟失了:
number = 1
print(id(number)) # 4325215472
print(id(1)) # 4325215472
number = 3
print(id(number)) # 4325215536
print(id(1)) # 4325215472

英文原文:https://towardsdatascience.com/100-helpful-python-tips-you-can-learn-before-finishing-your-morning-coffee-eb9c39e68958
推薦閱讀
國產(chǎn)小眾瀏覽器因屏蔽視頻廣告,被索賠100萬(后續(xù))
年輕人“不講武德”:因看黃片上癮,把網(wǎng)站和786名女主播起訴了
關(guān)于程序員大白
程序員大白是一群哈工大,東北大學(xué),西湖大學(xué)和上海交通大學(xué)的碩士博士運營維護的號,大家樂于分享高質(zhì)量文章,喜歡總結(jié)知識,歡迎關(guān)注[程序員大白],大家一起學(xué)習(xí)進步!


