我想將 b = {'a':234,'b':1,'c':2,'e':2387} 分別按照key和value進行排序,該怎樣辦呢?html
Python中比較經常使用的排序有兩個函數,python
1、定義數據結構
(1)一個是List數據結構中的sortless
>>> help(list.sort)
Help on method_descriptor:ide
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1函數
The sort() method takes optional arguments for controlling the comparisons.ui
cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.spa
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.htm
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.blog
In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.
Changed in version 2.3: Support for None as an equivalent to omitting cmp was added.
Changed in version 2.4: Support for key and reverse was added.
(2)內置的函數sorted
sorted(iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.
代表內置的sorted函數會生成一個新的數據表不會改變原有數據的順序。
The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).
cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.
2、舉例
>>>sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
>>> a = [5, 2, 3, 1, 4]
>>> a.sort() >>> a [1, 2, 3, 4, 5]
第一種使用的是內置排序方法,第二種是list的排序方法。Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.(雖然第一種方法不是很方便,可是一般更有效率)
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) [1, 2, 3, 4, 5]
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.
(另一點就是list.sort()的方法僅僅只能用做列表的數據結構,然而,sorted卻能夠用做任何可迭代的數據結構)
Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons(從2.4之後,新添加了key參數,經過制定一個判斷函數來按照key進行排序)
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
>>> student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
關於lambda實際上爲匿名函數,後面部分會將 lambda 函數參數:返回值
>>> class Student:
def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, self.grade, self.age)) def weighted_grade(self): return 'CBA'.index(self.grade) / float(self.age) >>> student_objects = [ Student('john', 'A', 15), Student('jane', 'B', 12), Student('dave', 'B', 10), ] >>> sorted(student_objects, key=lambda student: student.age) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.
Using those functions, the above examples become simpler and faster.
經過引入operator模塊有了更快的查詢方式:
>>> from operator import itemgetter, attrgetter, methodcaller
>>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
(咱們不只能夠按照一種條件進行排序,咱們還能夠設定多個條件進行排序,以下例中的先按照班級,在按照年齡)
>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
僅僅在後面添加一個reverse就能夠了
>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
回到剛開始的地方,咱們能夠很輕鬆的寫出:
import operator
def sortDict():
b = {'a':234,'b':1,'c':2,'e':2387}
print(sorted(b.iteritems(),key=operator.itemgetter(0)))#按key升序排列
print(sorted(b.iteritems(),key=operator.itemgetter(1)))#按value升序排列
print(sorted(b.items(),key=lambda x:x[1],reverse=True))##按value降序排列
輸出結果:
[('a', 234), ('b', 1), ('c', 2), ('e', 2387)][('b', 1), ('c', 2), ('a', 234), ('e', 2387)][('e', 2387), ('a', 234), ('c', 2), ('b', 1)]