Python索引的二级排序列表,来自多个列表的键
我正在尝试使用Python索引的二级排序列表,来自多个列表的键,python,python-3.x,Python,Python 3.x,我正在尝试使用list.sort()执行二次排序,下面是我的代码: index_list = list(range(12)) a_list = [5, 5, 5, 1, 2, 3, 3, 3, 3, 8, 8, 10] b_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 10] index_list.sort(key=lambda x:(a_list[x], b_list[x])) print(index_list) 结果是[3,4,5,6,7,8,0,1,
list.sort()
执行二次排序,下面是我的代码:
index_list = list(range(12))
a_list = [5, 5, 5, 1, 2, 3, 3, 3, 3, 8, 8, 10]
b_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 10]
index_list.sort(key=lambda x:(a_list[x], b_list[x]))
print(index_list)
结果是[3,4,5,6,7,8,0,1,2,9,10,11]
,而我预期最后三项是[…,10,9,11]
我认为它应该进行二次排序(基于b_list
的值),但似乎没有
编辑:已修复打字错误。您可以执行以下操作:
index_list.sort(key=lambda x:(a_list[x], -b_list[x])) # because -3 < 2 and by default it sorts in ascending order
你应使用:
index_list.sort(key=lambda x:(a_list[x], -b_list[x]))
而不是
index_list.sort(key=lambda x:(a_list[x], b_list[x]))
你为什么期望10,9,11?
b_列表中的第十个值是3,小于第九个值2。默认排序是从最小到最大,因此它将位于后面。什么c_列表
?在你的问题中,只有a_列表
和b_列表
。天哪,我没注意到!那是一个愚蠢的决定。谢谢
index_list.sort(key=lambda x:(a_list[x], b_list[x]))