The difference between sort and sorted in python

The difference between sort and sorted in python

We need to sort the List, Python provides two methods
to sort the given List L,
method 1. Sort with the member function sort of List
Method 2. Sort with the built-in function sorted (since 2.4)

− -------------------------------sorted------------------- ---------------------
>>> help(sorted)
Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp =None, key=None, reverse=False) --> new sorted list
--------------------------------- sort--------------------------------------------
>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1
-------------------------------------------------- ---------------------------

iterable: iterable type;
cmp: function for comparison, what to compare is determined by key, there is a default value, iterates an item in the collection;
key: uses a property and function of the list element as a key, with a default value, iterates an item in the collection;
reverse: the ordering rule. reverse = True or reverse = False, there are Defaults.
Return value: is a sorted iterable type, same as iterable.
 
Note; in general, cmp and key can use lambda expressions.

The difference between sort() and sorted() is that sort rearranges the list in place, while sorted() produces a new list.

Sorting basic:

>>> print sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
>>> L = [5, 2, 3, 1, 4]
>>> L.sort()
>>> print L
[1, 2, 3, 4, 5]

Sorting  cmp:

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print  sorted (L, cmp=lambda x,y:cmp(x[1],y[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

Sorting  keys:

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print  sorted (L, key=lambda x:x[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

Sorting  reverse:

>>> print sorted([5, 2, 3, 1, 4], reverse=True)
[5, 4, 3, 2, 1]
>>> print sorted([5, 2, 3, 1, 4], reverse=False)
[1, 2, 3, 4, 5]

Note: Efficiency key>cmp (key is faster than cmp)


In Sorting Keys: We see that the sorted L at this time is only sorted according to the second keyword. If we want to use the second keyword
What about sorting by the first keyword after sorting?
>>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> print sorted(L, key=lambda x:(x[1],x[0]))
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]

The above environment python2.4
Reprint address: http://www.cnblogs.com/65702708/archive/2010/09/14/1826362.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325693023&siteId=291194637