1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#http://falldog7.blogspot.com/2009/10/python-dictionary-or-classitemlistsort.html
d= [ {'id':0, 'value':9}, {'id':1, 'value':100}, {'id':5, 'value':99}, {'id':3, 'value':19}, {'id':2, 'value':59} ]
d.sort(key=lambda x:x['id']) #針對key 'id' 做sort
d.sort(key=lambda x:x['value']) #針對key 'value' 做sort
#以下用cmp,可以達到上面指定key的效果
d.sort(cmp=lambda x,y: cmp(x['id'], y['id']))
d.sort(cmp=lambda x,y: cmp(x['value'], y['value']))
class data:
def __init__(self, _id, _value):
self.id = _id
self.value = _value
c = [ data(0,9), data(1,100), data(5,99), data(3,19), data(2,59) ]
c.sort(key=lambda x:x.id)#針對class member id 做sort
c.sort(key=lambda x:x.value)#針對class member value 做sort
#以下用cmp,可以達到上面指定key的效果
c.sort(cmp=lambda x,y: cmp(x.id, y.id) )
c.sort(cmp=lambda x,y: cmp(x.value, y.value))
|