經(jīng)驗(yàn)豐富程序員才知道的8種高級Python技巧
本文轉(zhuǎn)載自公眾號“讀芯術(shù)”(ID:AI_Discovery)
本文將介紹8個(gè)簡潔的Python技巧,若非經(jīng)驗(yàn)十足的程序員,你肯定有些從未見過。向著更簡潔更高效,出發(fā)吧!
1.通過多個(gè)鍵值將對象進(jìn)行排序
假設(shè)要對以下字典列表進(jìn)行排序:
- people = [
- { 'name': 'John', "age": 64 },
- { 'name': 'Janet', "age": 34 },
- { 'name': 'Ed', "age": 24 },
- { 'name': 'Sara', "age": 64 },
- { 'name': 'John', "age": 32 },
- { 'name': 'Jane', "age": 34 },
- { 'name': 'John', "age": 99 },
- ]
不僅要按名字或年齡對其進(jìn)行排序,還要將兩個(gè)字段同時(shí)進(jìn)行排序。在SQL中,會(huì)是這樣的查詢:
- SELECT * FROM people ORDER by name, age
實(shí)際上,這個(gè)問題的解決方法可以非常簡單,Python保證sort函數(shù)提供了穩(wěn)定的排序順序,這也意味著比較相似的項(xiàng)將保留其原始順序。要實(shí)現(xiàn)按名字和年齡排序,可以這樣做:
- import operator
- people.sort(key=operator.itemgetter('age'))
- people.sort(key=operator.itemgetter('name'))
要注意如何反轉(zhuǎn)順序。首先按年齡分類,然后按名字分類,使用operator.itemgetter()從列表中的每個(gè)字典中獲取年齡和名字字段,這樣你就會(huì)得到想要的結(jié)果:
- [
- {'name': 'Ed', 'age': 24},
- {'name': 'Jane', 'age': 34},
- {'name': 'Janet','age': 34},
- {'name': 'John', 'age': 32},
- {'name': 'John', 'age': 64},
- {'name': 'John', 'age': 99},
- {'name': 'Sara', 'age': 64}
- ]
名字是主要排序項(xiàng),如果姓名相同,則以年齡排序。因此,所有John都按年齡分組在一起。
2.數(shù)據(jù)類別
自3.7版之后,Python開始能提供數(shù)據(jù)類別。比起常規(guī)類或其他替代方法(如返回多個(gè)值或字典),它有著更多優(yōu)點(diǎn):
- 數(shù)據(jù)類需要很少的代碼
- 可以比較數(shù)據(jù)類,因?yàn)?__eq__ 可以實(shí)現(xiàn)此功能
- 數(shù)據(jù)類需要類型提示,減少了發(fā)生錯(cuò)誤的可能性
- 可以輕松打印數(shù)據(jù)類以進(jìn)行調(diào)試,因?yàn)開_repr__可以實(shí)現(xiàn)此功能
這是一個(gè)工作中的數(shù)據(jù)類示例:
- from dataclasses import dataclass
- @dataclass
- classCard:
- rank: str
- suit: str
- card=Card("Q", "hearts")
- print(card == card)
- # True
- print(card.rank)
- # 'Q'
- print(card)
- Card(rank='Q', suit='hearts')
3.列表推導(dǎo)
列表推導(dǎo)可以在列表填寫里代替討厭的循環(huán),其基本語法為
- [ expression for item in list if conditional ]
來看一個(gè)非常基本的示例,用數(shù)字序列填充列表:
- mylist = [i for i inrange(10)]
- print(mylist)
- # [0, 1, 2, 3,4, 5, 6, 7, 8, 9]
因?yàn)榭梢允褂帽磉_(dá)式,所以你還可以進(jìn)行一些數(shù)學(xué)運(yùn)算:
- squares = [x**2for x inrange(10)]
- print(squares)
- # [0, 1, 4, 9,16, 25, 36, 49, 64, 81]
甚至能調(diào)用外部函數(shù):
- defsome_function(a):
- return (a +5) /2
- my_formula= [some_function(i) for i inrange(10)]
- print(my_formula)
- # [2.5, 3.0,3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
最后,可以使用if函數(shù)來篩選列表。在這種情況下,只保留可被2除的值:
- filtered = [i for i inrange(20) if i%2==0]
- print(filtered)
- # [0, 2, 4, 6,8, 10, 12, 14, 16, 18]
4.檢查對象的內(nèi)存使用情況
使用sys.getsizeof()可以檢查對象的內(nèi)存使用情況:
- import sys
- mylist =range(0, 10000)
- print(sys.getsizeof(mylist))
- # 48
為什么這個(gè)龐大的列表只有48個(gè)字節(jié)?這是因?yàn)閞ange函數(shù)返回的類表現(xiàn)為列表。與使用實(shí)際的數(shù)字列表相比,數(shù)序列的存儲(chǔ)效率要高得多。我們可以通過列表推導(dǎo)來創(chuàng)建相同范圍內(nèi)的實(shí)際數(shù)字列表:
- import sys
- myreallist = [x for x inrange(0, 10000)]
- print(sys.getsizeof(myreallist))
- # 87632
通過使用sys.getsizeof(),我們可以了解更多關(guān)于Python和內(nèi)存使用情況的信息。
5.查找最頻繁出現(xiàn)的值
要查找列表或字符串中最頻繁出現(xiàn)的值:
- test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
- print(max(set(test), key = test.count))
- # 4
- max()將返回列表中的最大值。key參數(shù)采用單個(gè)參數(shù)函數(shù)自定義排序順序,在本例中為test.count,該函數(shù)適用于迭代器上的每個(gè)項(xiàng)目。
- test.count是list的內(nèi)置功能。它接受一個(gè)參數(shù),并計(jì)算該參數(shù)的出現(xiàn)次數(shù)。因此test.count(1)將返回2,而test.count(4)將返回4。
- set(test)返回test中的所有唯一值,所以{1、2、3、4}
那么在這一行代碼將接受test的所有唯一值,即{1、2、3、4}。接下來,max將對其應(yīng)用list.count 函數(shù)并返回最大值。
還有一種更有效的方法:
- from collections import Counter
- Counter(test).most_common(1)
- # [4: 4]
6.屬性包
你可以使用attrs代替數(shù)據(jù)類,選擇attrs有兩個(gè)原因:
- 使用的Python版本高于3.7
- 想要更多功能
Theattrs軟件包支持所有主流Python版本,包括CPython 2.7和PyPy。一些attrs可以提供驗(yàn)證器和轉(zhuǎn)換器這種超常規(guī)數(shù)據(jù)類。來看一些示例代碼:
- @attrs
- classPerson(object):
- name =attrib(default='John')
- surname =attrib(default='Doe')
- age =attrib(init=False)
- p =Person()
- print(p)
- p=Person('Bill', 'Gates')
- p.age=60
- print(p)
- # Output:
- # Person(name='John', surname='Doe',age=NOTHING)
- # Person(name='Bill', surname='Gates', age=60)
實(shí)際上,attrs的作者已經(jīng)在使用引入數(shù)據(jù)類的PEP了。數(shù)據(jù)類被有意地保持得更簡單、更容易理解,而attrs 提供了可能需要的所有特性。
7.合并字典(Python3.5+)
- dict1 = { 'a': 1, 'b': 2 }
- dict2= { 'b': 3, 'c': 4 }
- merged= { **dict1, **dict2 }
- print (merged)
- # {'a': 1, 'b':3, 'c': 4}
如果有重疊的鍵,第一個(gè)字典中的鍵將被覆蓋。在Python 3.9中,合并字典變得更加簡潔。上面Python 3.9中的合并可以重寫為:
- merged = dict1 | dict2
8.返回多個(gè)值
Python中的函數(shù)在沒有字典,列表和類的情況下可以返回多個(gè)變量,它的工作方式如下:
- defget_user(id):
- # fetch user from database
- # ....
- return name, birthdate
- name, birthdate =get_user(4)
這是有限的返回值,但任何超過3個(gè)值的內(nèi)容都應(yīng)放入一個(gè)(數(shù)據(jù))類。
這8個(gè)小技巧足夠你好好消化一陣兒啦!