我的输入是这个列表:
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]
你们知道如何对我的列表进行排序吗?这种排序有名字吗?
试试这个:
result = sorted(my_list, key=lambda x: (x, my_list.index(x)))