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 I then resort against element to of course it ruins the previous sort. I can't do a combined key since it needs to first sort descending and then ascending.
使用itemgetter,我可以在元素0上反向传递,但我之后会使用元素,当然它会破坏之前的排序。我不能做组合键,因为它需要先下降然后上升。
TIA, PK
TIA,PK
3 个解决方案
#1
35
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]]
#2
31
You can do successive rounds of sorting as python's sort
is stable. You need to first sort on the secondary key though. See also the official HOW TO.
您可以进行连续的排序,因为python的排序是稳定的。不过,您需要首先对辅助键进行排序。还见官员如何。
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]]
#3
2
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()实现中的返回值可能被否定。
#1
35
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]]
#2
31
You can do successive rounds of sorting as python's sort
is stable. You need to first sort on the secondary key though. See also the official HOW TO.
您可以进行连续的排序,因为python的排序是稳定的。不过,您需要首先对辅助键进行排序。还见官员如何。
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]]
#3
2
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()实现中的返回值可能被否定。