如何对坐标列表进行排序?

How to sort the coordinate list?

假设我有一个坐标列表如下:

list_ = [{'x':1,'y':2},{'x':1,'y':1},{'x':3,'y':3}]

我想先排序x键,再排序y键。所以我预计:

list_ = [{'x':1,'y':1},{'x':1,'y':2},{'x':3:'y':3}]

我该怎么做?

使用sort/sortedkey参数。您传递一个 returns 作为排序依据的键的函数。 operator.itemgetter 是生成函数的有效方法:

>>> from operator import itemgetter
>>> list_ = [{'x':1,'y':2},{'x':1,'y':1},{'x':3,'y':3}]
>>> sorted(list_,key=itemgetter('x','y'))
[{'x': 1, 'y': 1}, {'x': 1, 'y': 2}, {'x': 3, 'y': 3}]