python 列表及字典(按key、按value排序)


python dict按照key 排序:

1、method 1.

items = dict.items()
items.sort()
for key,value in items:
   print key, value # print key,dict[key]

2、method 2.

print key, dict[key] for key in sorted(dict.keys())

 

python dict按照value排序:

method 1:

把dictionary中的元素分離出來放到一個list中,對list排序,從而間接實現對dictionary的排序。這個“元素”可以是key,value或者item。

method2:

#用lambda表達式來排序,更靈活:
sorted(dict.items(), lambda x, y: cmp(x[1], y[1]))
#降序
sorted(dict.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)

下面給出python內置sorted函數的幫助文檔:

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

python list排序:

list有sort方法:

  如:
   >>> s=[2,1,3,0]
   >>> s.sort()
   [0, 1, 2, 3]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM