3個 Python 編程技巧
今天分享 3 個 Python 編程小技巧,來看看你是否用過?
1、如何按照字典的值的大小進行排序
我們知道,字典的本質(zhì)是哈希表,本身是無法排序的,但 Python 3.6 之后,字典是可以按照插入的順序進行遍歷的,這就是有序字典,其中的原理,可以閱讀為什么 Python3.6 之后字典是有序的。
知道了這一點,就好辦了,先把字典的鍵值對列表排序,然后重新插入新的字典,這樣新字典就可以按照值的大小進行遍歷輸出。代碼如下:
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> for k,v in xs.items():#遍歷字典 ... print(k,v) ... a 4 b 3 c 2 d 1 >>> new_order = sorted(xs.items(), key=lambda x: x[1]) #對字典的鍵值對列表排序 >>> new_xs = { k : v for k,v in new_order} #有序列表插入新的字典 >>> new_xs {'d': 1, 'c': 2, 'b': 3, 'a': 4} >>> for k,v in new_xs.items(): ##新字典的輸出就是有序的 ... print(k,v) ... d 1 c 2 b 3 a 4
對列表的排序,你還可以使用如下方法:
>>> import operator >>> sorted(xs.items(), key=operator.itemgetter(1)) [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
2、優(yōu)雅的一次性判斷多個條件
假如有三個條件,只要有一個為真就可以通過,也許你會這么寫:
x, y, z = 0, 1, 0 if x == 1 or y == 1 or z == 1: print('passed')
實際上,以下三種方法更加 Pythonic
if 1 in (x, y, z): print('passed') if x or y or z: print('passed') if any((x, y, z)): print('passed')
最后一個用到了 Python
內(nèi)置的方法 any()
,any
接受一個可迭代對象作為參數(shù),比如列表或元組,只要其中一個為真,則 any() 方法返回真,用法示例如下:
>>> any(['a',(2,4),3,True]) True >>> any(['a',(2,4),3,False]) True >>> any(['a',(),3,False]) True >>> any(['',(),0,False]) False >>> any(('a',(),3,False)) True >>> any(('',(),0,False)) False ## 注意空的可迭代對象返回 False >>> any(()) False >>> any([]) False >>> any('') False >>> any({}) False
與 any()
對應(yīng)的,就是方法 all()
,只有全部為真,才為真,注意空的可迭代對象一直返回真。
>>> all(['a',(2,4),1,True]) //list都為"真" True >>> all(['a',(),1,True])//list元素中有空tuple False >>> all(['a',(2,4),0,True]) False >>> all(['a',(2,4),3,False]) False ## 注意空的可迭代對象返回 True >>>all([]) True >>> all(()) True >>> all({}) True >>> all('') True
查看幫助文檔,可以在解釋器輸入 help
:
>>> help(all) Help on built-in function all in module __builtin__: all(...) all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.
3、如何優(yōu)雅的合并兩個字典
** 操作符可以解包字典,這在合并字典時非常有用,比如:
>>> x = {'a': 1, 'b': 2} >>> y = {'b': 3, 'c': 4} >>> z = {**x, **y} >>> z {'c': 4, 'a': 1, 'b': 3}
如果在 Python2.x 中,需要這么做:
>>> z = dict(x, **y) >>> z {'a': 1, 'c': 4, 'b': 3}
以上就是3個 Python 編程技巧的詳細內(nèi)容,更多關(guān)于Python 編程技巧的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。