假设我有一个坐标列表如下:
list_ = [{'x':1,'y':2},{'x':1,'y':1},{'x':3,'y':3}]
我想先排序x
键,然后排序y
key 。所以我期望:
list_ = [{'x':1,'y':1},{'x':1,'y':2},{'x':3:'y':3}]
我该怎么办?
最佳答案
使用sort
/sorted
的key
参数。您传递一个返回要排序的键的函数。 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}]
关于python - 如何对坐标列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33293580/