python3字典排序__python

來源:互聯網
上載者:User
python3 字典排序

說實話,對字典進行排序,這個說法本身就有問題,實際上,你無法對操縱字典說,字典,在你的底層實現裡,你就得按照我指定的順序來排列,如果這樣的話,字典就喪失了它的速度優勢,它也不是一個字典了.

好了,廢話不多說,我這裡稍微記錄一下我的做法吧.

python2裡面原來是有dict.iteritems這樣一個函數的,但是在python3裡面給消除掉了,dict.itemitems實際返回的是一個list類型的對象,對象裡面全部是tuple元素,每個tuple都有兩個元素,一個是key,一個是value.

在python2時代的做法是這麼來排序的:

>> dic{'a':3 , 'b':2 , 'c': 1}>> sorted(dic.iteritems(), key=lambda x:x[0], reverse=True) # 按照第0個元素降序排列[('c', 1), ('b', 2), ('a', 3)]>> sorted(dic.iteritems(), key=lambda x:x[0], reverse=False) # 按照第0個元素升序排列[('a', 3), ('b', 2), ('c', 1)]>> sorted(dic.iteritems(), key=lambda x:x[1], reverse=True) # 按照第1個元素降序排列[('a', 3), ('b', 2), ('c', 1)]>> sorted(dic.iteritems(), key=lambda x:x[1], reverse=False) # 按照第1個元素降序排列[('c', 1), ('b', 2), ('a', 3)]

既然iteritems()函數取消了,我們構建一個類似的函數即可.

def dict2list(dic:dict):    ''' 將字典轉化為列表 '''    keys = dic.keys()    vals = dic.values()    lst = [(key, val) for key, val in zip(keys, vals)]    return lst

以後在python3裡面要對字典排個序什麼的,也很簡單:

>> dic{'a':3 , 'b':2 , 'c': 1}>> sorted(dict2list(dic), key=lambda x:x[0], reverse=True) # 按照第0個元素降序排列[('c', 1), ('b', 2), ('a', 3)]>> sorted(dict2list(dic), key=lambda x:x[0], reverse=False) # 按照第0個元素升序排列[('a', 3), ('b', 2), ('c', 1)]>> sorted(dict2list(dic), key=lambda x:x[1], reverse=True) # 按照第1個元素降序排列[('a', 3), ('b', 2), ('c', 1)]>> sorted(dict2list(dic), key=lambda x:x[1], reverse=False) # 按照第1個元素降序排列[('c', 1), ('b', 2), ('a', 3)]

至於效率,你都用python了,還扯什麼效率呢.

當然,也請不要奢望說,返回一個排序後的字典,前面已經講了,真的沒有意義,你是在追求順序的字典的話,可以使用有序字典,python裡面有這樣的包.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.