如何重新排列数字列表并保证子排序?

问题描述 投票:0回答:1

我的输入是这个列表:

my_list = [3, 1, 5, 4, 20, 21, 4, 3]

我的预期输出是这样的:

result = [1, 3, 4, 3, 4, 5, 20, 21]

我编写了下面的代码,但结果不同。

from collections import Counter

def count(item):
    return Counter(my_list)[item]

result = sorted(my_list, key=count)

print(result)

[1, 5, 20, 21, 3, 4, 4, 3]

你们知道如何对我的列表进行排序吗?这种排序有名字吗?

python list sorting
1个回答
-1
投票

试试这个:

result = sorted(my_list, key=lambda x: (x, my_list.index(x)))

© www.soinside.com 2019 - 2024. All rights reserved.