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

标签 python list python-2.7 sorting python-2.x

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

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/sortedkey参数。您传递一个返回要排序的键的函数。 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/

相关文章:

python - Django 国际化

Python Selenium 无法在网站中找到 ID

list - Dart混合类型列表

string - Pandas :将多列转换为字符串

python-2.7 - 使用Python ElementTree.register_namespace读取GPX?

python - 如何解决按顺序将文件附加到另一个文件时的内存问题

Python Gtk TreeView ;选择项目时如何刷新列表

python - 记住在提交之前运行测试

arrays - 在 scala 中更改列表类型的最佳方法

python - 如何在 python 中将 for 循环的增量设置为 1?