【问题标题】:Can we sort a list following several attributes? [duplicate]我们可以按照几个属性对列表进行排序吗? [复制]
【发布时间】:2019-09-19 11:54:47
【问题描述】:

假设我们有这个列表:

data=[[A, 5, 200], [B, 5, 220], [C, 4, 150], [D, 4, 150], [E, 1, 50]]

我们想用第一个数字(递增顺序)对它进行排序,如果是平局,则使用第二个数字(递减顺序),如果是平局,则按字母顺序。 我试过这段代码,但它不起作用:

data = sorted(data, key = operator.itemgetter(1, 2))

有没有更好的方法?

【问题讨论】:

  • 是子列表吗?看不到内部方括号内的逗号
  • 你似乎有非法的 python - 没有逗号,没有 ' 围绕字符串等。请准备一个 minimal reproducible example 以及你做了什么来解决它。

标签: python


【解决方案1】:

一般来说,您需要一个使用functools.cmp_to_key 更容易定义的键函数:

# Quick and dirty definition of cmp for Python 3
def cmp(a, b):
    """Return 0 if a == b, negative if a < b, and positive if a > b"""
    return (a > b) - (a < b)

def compare(a, b):
    return (cmp(a[1], b[1]) 
            or cmp(b[2], a[2])  # swap arguments for reversed ordering
            or cmp(a[0], b[0]))

sorted(data, key=functools.cmp_to_key(compare))

但是,您可以利用a &lt; b 隐含-a &gt; -b 的事实来编写

sorted(data, key=lambda a: (a[1], -a[2], a[0]))

【讨论】:

  • 我看不出这将如何处理决胜局lambda a, b: a[1] &lt; b[1] or a[2] &gt; b[2] or a[0] &lt; a[1])。不过,第二种解决方案有效
  • 是的,这需要一些工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2010-10-26
相关资源
最近更新 更多