看到的一个知识点,稍加记录…
数据格式
a = [{'name':'jk', 'score':4, 'first':1, 'second':2, 'third':2}, {'name':'zz', 'score':1, 'first':0, 'second':0, 'third': 1}, {'name': 'ns', 'score':4, 'first':1, 'second':0, 'third':4}]
处理要求
希望将上述的list
排序,按照每条记录中的'score'
排序。如果'score'
字段的值相等,则按照'first'
的值排序。如果'first'
依旧相等,则按照'second'
排序。如果'second'
相等,则按照'third'
字段的值来排序。
方法
>>> a.sort.__doc__
'L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1'
>>> def cmp(a1, a2):
... if a1['score'] != a2['score']:
... return a1['score'] - a2['score']
... elif a1['first'] != a2['first']:
... return a1['first'] - a2['first']
... elif a1['second'] != a2['second']:
... return a1['second'] - a2['second']
... else:
... return a1['third'] - a2['third']
...
>>>
>>>
>>>
>>> a.sort(cmp)
结果
>>> a
[{'second': 0, 'score': 1, 'name': 'zz', 'third': 1, 'first': 0}, {'second': 0, 'score': 4, 'name': 'ns', 'third': 4, 'first': 1}, {'second': 2, 'score': 4, 'name': 'jk', 'third': 2, 'first': 1}]