小編給大家分享一下Python有哪些編程技巧,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
我們知道,字典的本質是哈希表,本身是無法排序的,但 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)]假如有三個條件,只要有一個為真就可以通過,也許你會這么寫:
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 內置的方法 any() ,any 接受一個可迭代對象作為參數,比如列表或元組,只要其中一個為真,則 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() 對應的,就是方法 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.
** 操作符可以解包字典,這在合并字典時非常有用,比如:
>>> 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}看完了這篇文章,相信你對“Python有哪些編程技巧”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。