按python列表中的列表排序?

时间:2015-07-08 09:22:01

标签: python

我有一个这种类型的列表:

l = [{"id":"21", "region" :['2', '6', '4']}, {"id":"12", "region" :['1', '3', '8']}]

我想在“region”字段中对列表进行排序,也在第二个索引处对列表进行排序。 那就是:

l = [{"id":"21", "region" :['2', **'6'**, '4']}, {"id":"12", "region" :['1', **'3'**, '8']}]

我该怎么办?我知道itemgetter。但也无法做到这一点。

2 个答案:

答案 0 :(得分:2)

您可以将select t1.`month`, coalesce((t1.`income`-t2.`expenditure`),t1.`income`) as Savings from `income` t1 left join `expenditure` t2 on t1.`month`=t2.`month` order by t1.`month`; 与key参数一起使用,将lambda表达式传递给key参数 -

list.sort()

答案 1 :(得分:0)

参考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'}]