gpt4 book ai didi

Python:如何在数字初级排序中执行二级降序字母排序

转载 作者:太空狗 更新时间:2023-10-30 02:57:59 28 4
gpt4 key购买 nike

Sorting a Python list by two criteria Fouad 给出了如下答案:

sorted(list, key=lambda x: (x[0], -x[1]))

我想主要对元组列表中的以下列表进行排序,主要对每个元素中的第二个项目按升序排序,然后是第一个(字母)项目按降序排序:

[('Ayoz', 1, 18, 7), ('Aidan', 2, 4, 9), ('Alan', 2, 4, 9), ('Arlan', 5, 6, 7), ('Luke', 15, 16, 2), ('Tariq', 5, 4, 2)] 

给出答案:

[('Ayoz', 1, 18, 7), ('Alan', 2, 4, 9), ('Aidan', 2, 4, 9), ('Tariq', 5, 4, 2), ('Arlan', 5, 6, 7), ('Luke', 15, 16, 2)]

如果可能,使用上述方法。我试过了

tlist = [('Ayoz', 1, 18, 7), ('Aidan', 2, 4, 9), ('Alan', 2, 4, 9), ('Arlan', 5, 6, 7), ('Luke', 15, 16, 2), ('Tariq', 5, 4, 2)]
sorted(tlist, key=lambda elem: (elem[1], -elem[0]))

但这仅在 elem[0] 为数字时有效(在这种情况下它会给出 TypeError: bad operand type for unary -: 'str')

如有任何帮助,我将不胜感激。 Python版本为3.4

最佳答案

Python 中内置的排序例程是稳定的。也就是说,如果两个项目具有相同的键值,那么它们将保持彼此之间的顺序(靠近列表前面的那个仍然靠近前面)。因此,您可以使用多个排序 channel 对多个键进行排序。

from operator import itemgetter

tlist = [('Ayoz', 1, 18, 7), ('Aidan', 2, 4, 9), ('Alan', 2, 4, 9),
('Arlan', 5, 6, 7), ('Luke', 15, 16, 2), ('Tariq', 5, 4, 2)]

# sort by name in descending order
tlist.sort(key=itemgetter(0), reverse=True)
print('pass 1:', tlist)

# sort by element 1 in ascending order. If two items have the same value
# the names stay in the same order they had (descending order)
tlist.sort(key=itemgetter(1))
print(npass 2:', tlist)

打印:

pass 1: [('Tariq', 5, 4, 2), ('Luke', 15, 16, 2), ('Ayoz', 1, 18, 7), ('Arlan', 5, 6, 7), ('Alan', 2, 4, 9), ('Aidan', 2, 4, 9)]

pass 2: [('Ayoz', 1, 18, 7), ('Alan', 2, 4, 9), ('Aidan', 2, 4, 9), ('Tariq', 5, 4, 2), ('Arlan', 5, 6, 7), ('Luke', 15, 16, 2)]

关于Python:如何在数字初级排序中执行二级降序字母排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386922/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com