Sorting with lambda

Sorting list/Dic with lambda

1. Sort a List

sorted

1
sorted(iterable[,key][,reverse])

细节

list.sort()—> sort the list

sorted(list)—> return a sorted list

1
2
3
4
5
6
7
8
9
10
11
12
# Original list
L = ['c','a','b']

l2 = sorted(list)
# return a sorted list, but original list is not changed
# L2:['a', 'b', 'c']

l3 = sorted(list,reverse = True)
# L3: ['c','b','a']

L.sort()
# L itself has been sorted

2. Sort a dict?

Actually you cannot sort a dictionary, itself has no order.

But you can return a new sorted list

Example:

1
2
3
4
5
6
7
8
9
10
11
12
dic = {'c':1, 'b':2,'a':3}

L1 = sorted(dic)
# L1: ['a', 'b', 'c']
# sorted by key values and return to a list of keys

L2 = sorted(dic.values())
# L2:[1,2,3]

L3 = sorted(dic.items())
# L3: [('a', 3), ('b', 2), ('c', 1)]
# Return the list of the item tuples

2. Use lambda

Sort a list

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
L = [
{'x': 3, 'y': 2, 'z': 1},
{'x': 2, 'y': 1, 'z': 3},
{'x': 1, 'y': 3, 'z': 2},
]

#此处dic的意义:Every element in the list
L2 = sorted(L,key = lambda dic:dic['y'])
# L2: [{'x': 2, 'y': 1, 'z': 3}, {'x': 3, 'y': 2, 'z': 1}, {'x': 1, 'y': 3, 'z': 2}]

L.sort(key=lambda dic: dic[z])
# L:


# 用Method
>>> def getKey(item):
... return item[0]
>>> l = [[2, 3], [6, 7], [3, 34], [24, 64], [1, 43]]
>>> sorted(l, key=getKey)
[[1, 43], [2, 3], [3, 34], [6, 7], [24, 64]]

Sort a dict (return a list)

Example

1
2
3
4
5
6
7
8
9
dic = {
'a': {'x': 3, 'y': 2, 'z': 1},
'b': {'x': 2, 'y': 1, 'z': 3},
'c': {'x': 1, 'y': 3, 'z': 2},
}

L = sorted(dic, key = lambda k: dic[k]['y'])
# 推测:k是指every key value
# L:['b', 'a', 'c']