Python字典排序及小技巧

2021-09-11 07:19:37 字數 2115 閱讀 6569

不斷更新,加入在使用過程中積累的常用python一般語法及技巧

(1)輸出陣列的最後幾個元素:

print(myarray[-16:])  # 輸出myarray陣列的最後16個元素
(2)字典巢狀字典:

① 按照key值進行排序,sorted函式及lambda函式

python2中:可以按照外層字典key值排序;可以按照內層巢狀字典key值排序;不可以按照內層巢狀字典values值排序

>>> a = ,'m3':,'m0':,'m2':}

>>> b = sorted(a.items(), key=lambda x: x[0]) # 按照外層字典key值

>>> b

[('m0', ), ('m1', ), ('m2', ), ('m3', )]

>>> c = sorted(a.items(), key=lambda x: x[1]) # 按照內層巢狀字典的key值

>>> c

[('m1', ), ('m0', ), ('m3', ), ('m2', )]

python3中,可以按照外層字典key值排序;不可以按照內層巢狀字典key值排序;不可以按照內層巢狀字典values值排序

>>> a = ,'m3':,'m0':,'m2':}

>>> b = sorted(a.items(), key=lambda x: x[0])

>>> b

[('m0', ), ('m1', ), ('m2', ), ('m3', )]

>>> b = sorted(a.items(), key=lambda x: x[1])

traceback (most recent call last):

file "", line 1, in typeerror: '<' not supported between instances of 'dict' and 'dict'

查閱很多資料,這篇很全面。但是在dict巢狀dict中,用到的內部巢狀字典的key值需要保持相同,所以建議以後用到巢狀字典時,盡量使用內部key相同的字典。

>>> dic

, 'b': , 'c': }

>>> b = sorted(dic.items(), key=lambda x: x[1]['x'])

>>> b

[('c', ), ('b', ), ('a', )]

>>> b = sorted(dic.items(), key=lambda x: x[1]['y'])

>>> b

[('b', ), ('a', ), ('c', )]

>>> b = sorted(dic.items(), key=lambda x: x[1]['z'])

>>> b

[('a', ), ('c', ), ('b', )]

(3)巢狀列表排序,

# 按照列表第乙個元素排序

>>> a = [['usa', 'b'], ['china', 'c'], ['canada', 'd'], ['russia', 'a']]

>>> a.sort(key=lambda x: x[0])

>>> a

[['canada', 'd'], ['china', 'c'], ['russia', 'a'], ['usa', 'b']]

# 按照巢狀列表第二個元素排序

>>> a =

>>> b = sorted(a.items(), key=lambda x: x[1][1])

>>> b

[('d', [2, 1]), ('b', [0, 2]), ('a', [1, 3]), ('c', [3, 4])]

(4)字典經過排序後,型別變為list,不能再通過字典dict.items()訪問。

>>> a = , 'b': , 'c': }

>>> b = sorted(a.items(), key=lambda x: x[1]['x'])

>>> type(b)

>>> b

[('c', ), ('b', ), ('a', )]

python解字典技巧

k 1 k2 2 k3 3 k4 4 str1 k 1 k2 2 k3 3 k4 4 1.賦值字串 dict1 2.來個空字典 result str1.split 3.把 符號拆掉 print result k 1 k2 2 k3 3 k4 4 有點樣子了 for str2 in result 利用...

python實現字典排序 python 字典排序

引子 字典,形如 dic 字典中的元素沒有順序,所以dic 0 是有語法錯誤的。並且不可以有重複的鍵值,所以 dic.add c 4後,字典變成 待解決問題 如何根據需要可以根據 鍵 或 鍵值 進行不同順序的排序?函式原型 sorted dic,value,reverse dic為比較函式,valu...

python字典排序

1 準備知識 在python裡,字典dictionary是內建的資料型別,是個無序的儲存結構,每一元素是key value對 如 dict 其中 username 和 database 是key,而 password 和 master 是value,可以通過d key 獲得對應值value的引用,但...