例如,我有以下列表,其中每个元素的出现次数为:
apple - 3
banana - 4
orange - 2
列表:
["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"]
我需要按不带重复项的流行程度对列表进行排序,因此预期结果将是:
["banana", "apple", "orange"]
我考虑过创建一个以每个元素为键的字典,遍历列表,然后在每次找到键时都添加+1,所以我将以一个示例词典结尾:
dic = {"apple": 3, "banana": 4, "orange":2}
但是对于如何在没有重复的情况下对列表本身进行排序有点困扰。
谢谢。
编辑:谢谢大家,我不了解Counter。节日快乐!
答案 0 :(得分:4)
使用Counter:
from collections import Counter
data = ["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"]
counts = Counter(data)
result = sorted(counts, key=counts.get, reverse=True)
print(result)
输出
['banana', 'apple', 'orange']
答案 1 :(得分:4)
您可以使用collections.Counter
及其most_common
方法:
from collections import Counter
lst = ["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"]
res = [k for k, _ in Counter(lst).most_common()]
# ['banana', 'apple', 'orange']
答案 2 :(得分:1)
根据原始列表的计数对集合进行排序。编辑:正如评论中指出的那样,如果候选人很多,您可能想使用其他解决方案,多次调用列表的count方法并不是最佳选择。
a = ["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"]
sorted(set(a), key = lambda x: a.count(x), reverse = True) #reverse for descending
结果:
['banana', 'apple', 'orange']
答案 3 :(得分:0)
from itertools import groupby
L = ["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"] # Input list
counts = [(i, len(list(c))) for i,c in groupby(sorted(L))] # Create value-count pairs as list of tuples
counts = sorted(counts, key = lambda i: i[1] , reverse=True) #sort value-count list
out = [key for key, value in counts] #extract key
print (out)
答案 4 :(得分:0)
使用list
和set
a = ["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"]
result =sorted(list(set(a)))
输出:
['apple', 'banana', 'orange']