按出现次数对列表进行排序并删除重复项

例如,我有以下列表,其中每个元素的出现次数是:


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}

但是有点卡住了如何在没有欺骗的情况下对列表本身进行排序..


提前致谢。


编辑:谢谢大家,我不知道计数器。节日快乐!


幕布斯6054654
浏览 208回答 3
3回答

陪伴而非守候

您可以使用 acollections.Counter及其most_common方法:from collections import Counterlst = ["apple", "apple", "banana", "orange", "orange", "banana", "banana", "apple", "banana"]res = [k for k, _ in Counter(lst).most_common()]# ['banana', 'apple', 'orange']

慕尼黑8549860

使用计数器:from collections import Counterdata = ["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']

慕斯709654

根据原始列表的计数对集合进行排序。编辑:正如评论中所指出的,如果您有很多候选人,您可能想要使用其他解决方案,多次调用列表的计数方法不是最佳选择。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']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python