简体   繁体   English

排序列表升序然后降序

[英]Sort list of lists ascending and then descending

If I have a list that contains a list that looks like this如果我有一个列表,其中包含一个看起来像这样的列表

['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]

How can I sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like如何对它们进行排序,以便元素 0 降序排序,元素 1 升序排序,这样结果看起来像

['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3]

Using itemgetter I can pass in reverse on element 0 but I then resort against element to of course it ruins the previous sort.使用itemgetter我可以在元素 0 上反向传递,但然后我使用元素当然会破坏之前的排序。 I can't do a combined key since it needs to first sort descending and then ascending.我不能做一个组合键,因为它需要先降序然后升序。

L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]]
L.sort(key=lambda k: (k[0], -k[1]), reverse=True)

L now contains: L现在包含:

[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]

You can do successive rounds of sorting as python's sort is stable .可以进行连续几轮排序,因为 python 的sortstable You need to first sort on the secondary key though.不过,您需要先对辅助键进行排序。 See also the official HOW TO .另请参阅官方 HOW TO

from operator import itemgetter
l = [['a',2], ['a',1], ['b', 2], ['a',3], ['b',1], ['b',3]]
l.sort(key=itemgetter(1))
l.sort(key=itemgetter(0), reverse=True)
# [['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]

Something like就像是

def mycmp(a, b):

  res = cmp(a[0], b[0])
  if res == 0:
     return cmp(a[1], b[1])
  return res

newlist = sorted(input_list, cmp=mycmp)

The comparison method first checks the first item of each element.比较方法首先检查每个元素的第一项。 If they are equal it will check the second items of each element.如果它们相等,它将检查每个元素的第二项。 The return value inside the mycmp() implementation may be negated in order to implemented a different sorting behavior.为了实现不同的排序行为,mycmp() 实现中的返回值可能会被取反。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM