Python-Sorted()

**Python --sorted()**
sorted() and sort():
  • sort() is only for list, while sorted() can sort all iterable objects.
  • sort() has not return value, sorting the original list, sorted will return a new sorted list, and the original list stay unchanged.
Definition:

sorted(iterable[, cmp[, key[, reverse]]])
note: arguments in [] are optional. And python3 doesn’t have cmp argument anymore.

  • iterable: iterable objects, like list, dict, set.
  • cmp: a custom comparison function. The default value is None.
  • key: specifies a function of one argument that is used to compare. The default value is None (compare the elements directly).
  • reverse: a boolean value. The default value is False(ascending order). If you want descending order, set reverse = True.
Usage:

Sort multiple dimensional lists:

1
2
3
l = [(1,'a'), (2,'v'), (4, 'd'), (3, 's')]      
sorted(l, cpm = lambda x, y: cpm(x[1], y[1]) # using cmp (only in python2)
sorted(l, key = lambda x: x[1]) # using key (both python2 and python3)
The usage of key:
1
2
3
4
5
6
7
8
9
sorted(l, key = len) # sort list according to the length of elements  
sorted(l, key = str.lower) # change the str in list to be lower, then sort
s = ['sd', 'cs', 'ee']
def lastchar(s): # return the last character of s
return s[-1]
sorted(s, key = lastchar) # sort according to the last character of every element in s
sorted(s, key = lambda x: x[-1]) # same as above
d = [{'name':'abc','age':20}, {'name':'mary','age':30}, {'name':'bob','age':25}]
sorted(d, key = lambda x: x['age']) # sort according to age in each dict
0%