是否有 python 函数用于根据嵌套数组中的两个元素对二维数组进行排序?

Is there a python function for sorting a 2D array based on both elements in the nested array?

所以我有一个如下所示的列表:people_list = [[str name, int numerical value]] 其中 people_list 中有 n 个列表。使用实际数据,它看起来像这样:people_list = [['jim', 30000], ['james', 30000]]。我需要首先根据每个嵌套列表中的数值对这个列表进行排序,因此根据 people_list[i][1] 进行排序,其中 i 是第 n 个嵌套列表,整个 people_list needs 从中排序从最高到最低的数值。然后,如果数值有任何联系,我需要根据名称按字母顺序对联系列表进行排序,因此 people_list[i][0].

我尝试了下面的代码进行排序,但输出结果并不完全符合我的需要,而且我还没有在网上找到任何其他资源来让它按照我的需要进行排序。

people_list = [['jim', 33000], ['james', 22000], ['john', 33000], ['zack', 10000]]
sorted_by_int_then_name = sorted(people_list, key=lambda person: (person[1], person[0]), reverse=True)

此代码的输出是:

>>> sorted_by_int_then_name
[['john', 33000], ['jim', 33000], ['james', 22000], ['zack', 10000]]

这是按数字正确排序的,但名字没有按照我需要的那样按字母顺序排序。我认为我遇到的问题可能是因为我使用的是 reverse=True 参数,但如果我不包含该参数,则列表将从最低数值到最高排序。我正在寻找的输出是这样的:

>>> sorted_by_int_then_name
[['jim', 33000], ['john', 33000], ['james', 22000], ['zack', 10000]]

如何正确地按 people_list[i][1] 的数值排序,然后在数值相近时按 people_list[i][0] 正确排序?

我 运行 此代码在 Ubuntu 20.04.3 LTS

上使用 python 版本 3.8.10

一种方法是将整数乘以 -1 而不是使用 reverse=True:

people_array = [['jim', 33000], ['james', 22000], ['john', 33000], ['zack', 10000]]
sorted_by_int_then_name = sorted(people_array, key=lambda person: (-1 * person[1], person[0]))
print(sorted_by_int_then_name)

输出

[['jim', 33000], ['john', 33000], ['james', 22000], ['zack', 10000]]

作为替代方案,并利用 sorted is stable 这一事实,使用两次排序:

from operator import itemgetter

people_array = [['jim', 33000], ['james', 22000], ['john', 33000], ['zack', 10000]]
sorted_by_int_then_name = sorted(people_array, key=itemgetter(0))
sorted_by_int_then_name.sort(key=itemgetter(1), reverse=True)
print(sorted_by_int_then_name)

输出

[['jim', 33000], ['john', 33000], ['james', 22000], ['zack', 10000]]

两次排序可以更快,参见