Python初學者必學的20個重要技巧
本文轉載自公眾號“讀芯術”(ID:AI_Discovery)。
Python是世界上使用最廣泛的編程語言之一,原因有很多:易理解、用途非常廣泛、包含了大量的模塊和庫等等。其中,簡潔和較高的可讀性使Python在所有軟件中非常突出。
作為一名數據科學家,筆者每天都在使用Python,這是筆者工作的一個重要部分。在這個過程中,筆者學會了一些驚人的技巧。
1. 交換價值
數字交換通常涉及存儲在臨時變量中的值。然而,我們可以通過使用Python技巧中的一行代碼,不需要使用瞬變變量就可以實現這一點。
- """valueswapping"""
- a, b=5, 10
- print(a, b) a, bb= b, a print(a, b) output 10, 5
2. 列表中所有項的一個字符串
必須對一個字符串列表進行卷積時,可以通過for循環來更新每一項以此連續不斷地執行此操作。然而這樣做很麻煩,特別是在列表很長的情況下。在Python中,字符串是不可變的。因此,在每兩個拼接中,左字符串和右字符串都應該被復制成一個新的字符串。
如下所示,使用join()函數是一種更為簡潔的解決方法:
- p = ["Python", "is", "a","popular", "language"]
- print(" ".join(p))output
- Python is a popular language
3. 列表中最常見的元素
確定列表中最經常出現的值。如果不同的項目以相同的方式出現,則打印其中的一個。創建列表集以刪除冗余值。因此在集合中能找到每一項的最大事件數,然后再考慮最大的。
- list1 = [0, 1, 2, 3, 3, 2, 3, 1, 4, 5, 4]
- print(max(set(list1), key = list1.count))output
- 3
4. 測試兩個字符串是否為相同字母異序詞
- defanagram(string_1,string_2):
- """Test if the stringsare anagrams.
- string_1: string
- string_2: string
- returns: boolean
- """
解決上述問題,從而弄清楚兩個字符串是否是相同字母異序詞。給定兩個字符串string_1 和string_2,測試這兩個字符串是否互為相同字母異序詞。
- from collections importCounter
- defanagram(string_1,string_2): returnCounter(string_1) ==Counter(string_2) anagram('pqrs','rqsp')
- True
- anagram('pqrs','rqqs')
- False
圖源:unsplash
5. 逆轉字符串
切片是Python中的一種方便技巧,它還可以用于逆轉字符串中項的順序。
- # with slicing
- str ="PQRST"
- reverse_str = str[::-1]
- print(reverse_str) Output TSRQP
6. 反轉列表
使用這種方法創建列表的副本,而且列表沒有按順序排序。要創建一個副本,需要更多的空間來容納所有現有的元素。
- # using slicing approach
- defReverse(lst): lstlst1 = lst[::-1]
- return lst1
- lst = [5, 6, 7, 8, 9, 10]
- print(Reverse(lst))
- output
- [10, 9, 8, 7, 6, 5]
7. 轉置矩陣
轉置矩陣意味著將列變換為行,反之亦然。使用Python,可以通過以下代碼與zip函數結合,并使用*工具解壓縮矩陣的轉置列表。
- mat=[(5,6,7),(8,9,10),(11,12,13),(14,15,16)]
- for row in mat:
- print(row)
- print("\n")
- t_mat=zip(*mat)
- for row in t_mat:
- print(row)
- output
- (5, 6, 7)
- (8, 9, 10)
- (11, 12, 13)
- (14, 15, 16)
- (5, 8, 11, 14)
- (6, 9, 12, 15)
- (7, 10, 13, 16)
8. 鏈式比較
在編程中,測試兩個以上的條件是很正常的。假設需要測試以下內容:
- p < q< r
更聰明的做法確實是在Python中通過鏈式來編寫。任務鏈表示如下:
- if p< q< r:
- {.....}
返回布爾值來比較判斷正確與否。示例如下:
- # chaining comparison
- a =3
- print(1< a<10)
- print(5< a<15)
- print(a <7< a*7<49)
- print(8> a<=6)
- print(3== a>2)
- output
- True
- False
- True
- True
- True
9. ‘get’字典
下面是訪問Python字典中鍵值的傳統方法:
- dict = {"P":1, "Q":2}
- print(dict["P"])
- print(dict["R"])
代碼的第三行會產生一個關鍵錯誤:
- Traceback (most recent call last):
- File ".\dict.py", line 3, in
- print (dict["R"])
- KeyError: 'R'
為了防止這種情況的出現,可以使用get()函數。當在字典中可用時,該技巧可以提供特定鍵的值。若不可用,則不會返回任何值(如果 get()只使用了一個參數)。
- dict = {"P":1, "Q":2}
- print(dict.get("P"))
- print(dict.get("R"))
- print(dict.get("R","Unavailable! "))
- output 1
- None
- Unavailable!
10. 按值給字典排序
排序在日常編程中一直是很有用的。Python中的字典在許多應用程序中被廣泛使用,范圍從競爭領域到開發人員領域。構造一本字典,并按字母順序顯示所有鍵,按值列出按字母順序排序的鍵和值。
- defdict():
- keyval ={} # Initializing the value keyval[3] =48
- keyval[2] =6
- keyval[5] =10
- keyval[1] =22
- keyval[6] =15
- keyval[4] =245
- print ("Task3:-\nKeys and Values sorted",
- "in alphabetical order by thevalue")
- # Remember this would arrange inaphabetical sequence # Convert it to float to mathematicalpurposes print(sorted(keyval.elements(), key =
- lambda k_val:(k_val[1], k_val[0])))
- defmain(): dict() if __name__=="__main__":
- main() output
- [(2, 6), (5, 10), (6, 15), (1, 22), (3, 48), (4, 245)]
圖源:unsplash
11. 列表推導
要從不同的迭代中構造新的列表,需要使用列表推導。由于列表推導式產生列表,因此它們包含表達式的括號,該表達式將被執行到每個元素。推導列表更簡單,因為Python解釋器旨在檢測循環中的循環模式。
- # Multiplying each item in the list with 3
- list1 = [2,4,6,8]
- list2 = [3*p for p in list1]
- print(list2)
- [6,12,18,24]
12. 執行部分計劃所花費的時間
這個重點展示了計算程序或程序的一部分執行所花費的時間。計算時間有助于優化Python腳本,使其執行得更好。
- import time
- initial_Time = time.time()
- # Program to test follows x, y=5,6
- z = x+ y # Program to test ending ending_Time = time.time()
- Time_lapsed_in_Micro_sec= (ending_Time- initial_Time)*(10**6)
- print(" Timelapsed in micro_seconds: {0} ms").format(Time_lapsed_in_Micro_sec)
13. 合并字典
這是Python中的一個重要技巧:使用一個表達式來合并兩個字典并將結果存儲在第三個字典中。單個表達式是 **,這不會影響其他兩個字典。**表示參數是一個字典。使用**是一種快捷方式,這樣就可以通過使用字典直接向函數傳遞多個參數。
使用這個函數,首先將第一個字典的所有元素傳遞給第三個字典,然后將第二個字典傳遞給第三個字典。這將替換第一個字典的重復鍵
- dic1 = {'men': 6, 'boy': 5}
- dic2 = {'boy': 3, 'girl': 5}
- merged_dic = {**dic1, **dic2}
- print(merged_dic)
- Output
- {'men': 6, 'boy': 3, 'girl': 5}
14. 數字化
下面是使用了 map()函數、列表推導以及一種更簡單的數字化方法編寫的代碼:
- number =2468
- # with map
- digit_list =list(map(int, str(number)))
- print(digit_list) [2, 4, 6, 8]
- # with list comprehension
- digit_list = [int(a) for a instr(number)]
- print(digit_list) [2, 4, 6, 8]
- # Even simpler approach digit_list =list(str(number))
- print(digit_list) [2, 4, 6, 8]
15. 測試獨特性
一些列表操作要求測試列表中的所有項是否完全不同。嘗試在列表中執行集合操作時,通常會發生這種情況,這個特殊的實用程序在這時必不可少。
- defuniq(list):
- iflen(list)==len(set(list)): print("totalitems are unique")
- else:
- print("Listincludes duplicate item")
- uniq([0,2,4,6])
- total items are unique uniq([1,3,3,5])
- List includesduplicate item
16. 使用枚舉
在循環中使用枚舉數可以快速查找索引:
- sample_list = [4, 5, 6]
- for j, item inenumerate(sample_list):
- print(j, ': ', item)
- Output
- 0 : 4
- 1 : 5
- 2 : 6
17. 在一行中計算任意數的階乘
此技巧可以幫助你在一行中找到一個給定數的階乘:
- import functools
- fact = (lambda i: functools.reduce(int.__mul__, range(1,i+1),1)(4)
- print(fact)
- Output 24
18. 返回幾個函數的元素
許多計算機語言都不提供這個功能。但是對于Python,函數會產生幾個元素。查看下面的實例,了解它是如何執行的:
- # function returning several elements.
- defa():
- return5, 6, 7, 8
- # Calling the abovefunction.
- w, x, y, z=a()
- print(w, x, y, z)
- Output
- 5678
19. 加入一個真正的Python切換大小寫語句
下面是使用字典復制大小寫轉換結構的腳本:
- defaswitch(a):
- returnaswitch._system_dic.get(a, None)
- aswitch._system_dic = {'mangoes': 4, 'apples': 6, 'oranges': 8}
- print(aswitch('default'))
- print(aswitch('oranges'))
- Output None
- 8
20. 使用splat操作符解包函數參數
splat操作符提供了一種解包參數列表的有效方法:
- deftest(a, b, c):
- print(p, q, r)
- test_Dic = {'a': 4, 'b': 5, 'c': 6}
- test_List = [10, 11, 12] test(*test_Dic)
- test(**test_Dic)
- test(*test_List)
- #1-> p q r
- #2-> 4 5 6
- #3-> 10 11 12
掌握這些小技巧,快速有效地完成Python任務。