3 回答
TA贡献1757条经验 获得超8个赞
您可以使用 acollections.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']
TA贡献1818条经验 获得超11个赞
使用计数器:
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']
TA贡献1840条经验 获得超5个赞
根据原始列表的计数对集合进行排序。编辑:正如评论中所指出的,如果您有很多候选人,您可能想要使用其他解决方案,多次调用列表的计数方法不是最佳选择。
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']
添加回答
举报