值得收藏,Python 開(kāi)發(fā)中的高級(jí)技巧
Python 開(kāi)發(fā)中有哪些高級(jí)技巧?這是知乎上一個(gè)問(wèn)題,我總結(jié)了一些常見(jiàn)的技巧在這里,可能談不上多高級(jí),但掌握這些至少可以讓你的代碼看起來(lái) Pythonic 一點(diǎn)。如果你還在按照類C語(yǔ)言的那套風(fēng)格來(lái)寫(xiě)的話,在 code review 恐怕會(huì)要被吐槽了。
列表推導(dǎo)式
>>> chars = [ c for c in 'python' ] >>> chars ['p', 'y', 't', 'h', 'o', 'n']
字典推導(dǎo)式
>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} >>> double_dict1 = {k:v*2 for (k,v) in dict1.items()} >>> double_dict1 {'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}
集合推導(dǎo)式
>>> set1 = {1,2,3,4} >>> double_set = {i*2 for i in set1} >>> double_set {8, 2, 4, 6}
合并字典
>>> x = {'a':1,'b':2} >>> y = {'c':3, 'd':4} >>> z = {**x, **y} >>> z {'a': 1, 'b': 2, 'c': 3, 'd': 4}
復(fù)制列表
>>> nums = [1,2,3] >>> nums[::] [1, 2, 3] >>> copy_nums = nums[::] >>> copy_nums [1, 2, 3]
反轉(zhuǎn)列表
>>> reverse_nums = nums[::-1] >>> reverse_nums [3, 2, 1] PACKING / UNPACKING
變量交換
>>> a,b = 1, 2 >>> a ,b = b,a >>> a 2 >>> b 1
高級(jí)拆包
>>> a, *b = 1,2,3 >>> a 1 >>> b [2, 3]
或者
>>> a, *b, c = 1,2,3,4,5 >>> a 1 >>> b [2, 3, 4] >>> c 5
函數(shù)返回多個(gè)值(其實(shí)是自動(dòng)packing成元組)然后unpacking賦值給4個(gè)變量
>>> def f(): ... return 1, 2, 3, 4 ... >>> a, b, c, d = f() >>> a 1 >>> d 4
列表合并成字符串
>>> " ".join(["I", "Love", "Python"]) 'I Love Python'
鏈?zhǔn)奖容^
>>> if a > 2 and a < 5: ... pass ... >>> if 2<a<5: ... pass yield from # 沒(méi)有使用 field from def dup(n): for i in range(n): yield i yield i # 使用yield from def dup(n): for i in range(n): yield from [i, i] for i in dup(3): print(i) >>> 0 0 1 1 2 2
in 代替 or
>>> if x == 1 or x == 2 or x == 3: ... pass ... >>> if x in (1,2,3): ... pass
字典代替多個(gè)if else
def fun(x): if x == 'a': return 1 elif x == 'b': return 2 else: return None def fun(x): return {"a": 1, "b": 2}.get(x)
有下標(biāo)索引的枚舉
>>> for i, e in enumerate(["a","b","c"]): ... print(i, e) ... 0 a 1 b 2 c
生成器
注意區(qū)分列表推導(dǎo)式,生成器效率更高
>>> g = (i**2 for i in range(5)) >>> g <generator object <genexpr> at 0x10881e518> >>> for i in g: ... print(i) ... 0 1 4 9 16
默認(rèn)字典 defaultdict
>>> d = dict() >>> d['nums'] KeyError: 'nums' >>> >>> from collections import defaultdict >>> d = defaultdict(list) >>> d["nums"] []
字符串格式化
>>> lang = 'python' >>> f'{lang} is most popular language in the world' 'python is most popular language in the world'
列表中出現(xiàn)次數(shù)最多的元素
>>> nums = [1,2,3,3] >>> max(set(nums), key=nums.count) 3
或者
from collections import Counter >>> Counter(nums).most_common()[0][0] 3
讀寫(xiě)文件
>>> with open("test.txt", "w") as f: ... f.writelines("hello")
判斷對(duì)象類型,可指定多個(gè)類型
>>> isinstance(a, (int, str)) True
類似的還有字符串的 startswith,endswith
>>> "http://foofish.net".startswith(('http','https')) True >>> "https://foofish.net".startswith(('http','https')) True __str__ 與 __repr__ 區(qū)別 >>> str(datetime.now()) '2018-11-20 00:31:54.839605' >>> repr(datetime.now()) 'datetime.datetime(2018, 11, 20, 0, 32, 0, 579521)'
前者對(duì)人友好,可讀性更強(qiáng),后者對(duì)計(jì)算機(jī)友好,支持 obj == eval(repr(obj))
使用裝飾器
def makebold(f): return lambda: "<b>" + f() + "</b>" def makeitalic(f): return lambda: "<i>" + f() + "</i>" @makebold @makeitalic def say(): return "Hello" >>> say() <b><i>Hello</i></b>
不使用裝飾器,可讀性非常差
def say(): return "Hello" >>> makebold(makeitalic(say))() <b><i>Hello</i></b>
總結(jié)
以上所述是小編給大家介紹的Python 開(kāi)發(fā)中的高級(jí)技巧,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
pygame實(shí)現(xiàn)一個(gè)類似滿天星游戲流程詳解
這篇文章主要介紹了使用pygame來(lái)編寫(xiě)類滿天星游戲的全記錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-09-09Python實(shí)現(xiàn)操作Redis的高級(jí)用法分享
redis-py是Python操作Redis的第三方庫(kù),它提供了與Redis服務(wù)器交互的API,本文為大家介紹了Python利用redis-py操作Redis的高級(jí)用法,需要的可以收藏一下2023-05-05python人工智能深度學(xué)習(xí)入門(mén)邏輯回歸限制
這篇文章主要為大家介紹了python人工智能深度學(xué)習(xí)入門(mén)之邏輯回歸限制的詳細(xì)講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11python實(shí)現(xiàn)定時(shí)發(fā)送郵件
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)定時(shí)發(fā)送郵件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12python數(shù)據(jù)類型的詳細(xì)分析(附示例代碼)
這篇文章主要給大家介紹了關(guān)于python數(shù)據(jù)類型分析的相關(guān)資料,python里可以通過(guò)type()函數(shù)來(lái)查看數(shù)據(jù)類型,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09Python實(shí)現(xiàn)自定義順序、排列寫(xiě)入數(shù)據(jù)到Excel的方法
這篇文章主要介紹了Python實(shí)現(xiàn)自定義順序、排列寫(xiě)入數(shù)據(jù)到Excel的方法,涉及Python針對(duì)Excel文件的數(shù)據(jù)處理及讀寫(xiě)相關(guān)操作技巧,需要的朋友可以參考下2018-04-04