日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

字典排序什么意思_字典排序问题

發(fā)布時間:2025/3/8 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 字典排序什么意思_字典排序问题 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2018-01-03@望京

排序,立即想到用Python的內(nèi)置函數(shù)sorted()

Python 2.x 中

sorted(...)

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

Python 3.x 中

sorted(iterable, key=None, reverse=False)

Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the

reverse flag can be set to request the result in descending order.

字典按key排序

>>> dic = {'a':9, 'c':3, 'f':12, 'b':1, 'd':7}

>>>

>>> sorted(dic)

['a', 'b', 'c', 'd', 'f']

>>>

>>> sorted(dic.keys())

['a', 'b', 'c', 'd', 'f']

>>>

>>> sorted(dic.values())

[1, 3, 7, 9, 12]

>>>

>>> sorted(dic.items())

[('a', 9), ('b', 1), ('c', 3), ('d', 7), ('f', 12)]

>>>

>>> for k in sorted(dic):

... print dic[k]

...

9

1

3

7

12

>>>

字典是無序的,對字典排序本身是一個沒有太大意義的事,但是面試的時候總會遇到==''

那么問題來了,如何對字典按照value排序呢(默認(rèn)是對key進(jìn)行排序)?

首先需要知道sorted()這個函數(shù)的幾個參數(shù)的意思(按照Python 3.x來說明):

- iterable? ?指的是可迭代對象,可以是dic,dic.items(), dic.keys(),? dic.values() 等等;

- key? ? ? ? ?key對應(yīng)一個函數(shù),用來選取參與比較的元素;

-?reverse? ?排序規(guī)則. reverse = True 或者 reverse = False(默認(rèn)值);

Py2中使用sort的cmp參數(shù)自定義排序方式

>>>

>>> res = [{'name':'hi','age':10},{'name':None,'age':10},{'name':'bo','age':10},{'name':'aaa','age':10}]

>>>

>>> res.sort(cmp=lambda x, y: cmp(x['name'], y['name']))

>>>

>>> res

[{'age': 10, 'name': None}, {'age': 10, 'name': 'aaa'}, {'age': 10, 'name': 'bo'}, {'age': 10, 'name': 'hi'}]

>>>

使用key參數(shù)來實現(xiàn)

items()方法將字典的元素 轉(zhuǎn)化為了元組

>>> dic

{'a': 9, 'c': 3, 'b': 1, 'd': 7, 'f': 12}

>>> dic.items()

[('a', 9), ('c', 3), ('b', 1), ('d', 7), ('f', 12)]

>>>

>>> sorted(dic.items())

[('a', 9), ('b', 1), ('c', 3), ('d', 7), ('f', 12)]

>>>

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

[('b', 1), ('c', 3), ('d', 7), ('a', 9), ('f', 12)]

>>>

使用zip來實現(xiàn)

>>> dic

{'a': 9, 'c': 3, 'b': 1, 'd': 7, 'f': 12}

>>>

>>> new_dic = zip(dic.values(), dic.keys())

>>>

>>> new_dic

[(9, 'a'), (3, 'c'), (1, 'b'), (7, 'd'), (12, 'f')]

>>>

>>> sorted(new_dic)

[(1, 'b'), (3, 'c'), (7, 'd'), (9, 'a'), (12, 'f')]

>>>

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結(jié)

以上是生活随笔為你收集整理的字典排序什么意思_字典排序问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。