【问题标题】:How to sort the coordinate list? [duplicate]如何对坐标列表进行排序? [复制]
【发布时间】:2015-10-23 01:45:51
【问题描述】:

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

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}]

我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    使用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}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 2016-12-31
      • 1970-01-01
      • 2018-07-21
      • 2016-03-21
      相关资源
      最近更新 更多