Sort by list in list in python?
This question already has an answer here:
你可以使用带键参数的list.sort()
,将一个lambda表达式传递给key参数 -
In [45]: l = [{"id":"21", "region" :['2', '6', '4']}, {"id":"12", "region" :['1', '3', '8']}]
In [46]: l.sort(key=lambda x: x['region'][1])
In [47]: l
Out[47]:
[{'id': '12', 'region': ['1', '3', '8']},
{'id': '21', 'region': ['2', '6', '4']}]
参考sorted(iterable, cmp=None, key=None, reverse=False)
>>> l = [{"id":"21", "region" :['2', '6', '4']}, {"id":"12", "region" :['1', '3', '8']}]
>>> print sorted(l, key=lambda x: x['region'][1], reverse=False)
[{'region': ['1', '3', '8'], 'id': '12'}, {'region': ['2', '6', '4'], 'id': '21'}]
>>> print l
[{'region': ['2', '6', '4'], 'id': '21'}, {'region': ['1', '3', '8'], 'id': '12'}]
链接地址: http://www.djcxy.com/p/70776.html
上一篇: 按特定字典键对字典列表进行排序
下一篇: 按列表在Python中排序?