【问题标题】:Python3 - how can I sort the list by frequency of its elements? [duplicate]Python3 - 如何按元素的频率对列表进行排序? [复制]
【发布时间】:2019-05-12 04:01:04
【问题描述】:

我正在编写可以分析输入文本的代码。 我想寻求帮助的功能之一是按频率降序列出使用的单词。

通过引用堆栈溢出中的相似主题,我能够仅保留字母数字字符(删除所有引号/标点符号等)并将每个单词放入列表中。

这是我现在的清单。 (名为 word_list 的变量)

['Hi', 'beautiful', 'creature', 'Said', 'by', 'Rothchild', 'the', '最大','敌人','之','尊','尊','开始','得到','害怕', 'of','他','As','her','best','friend','Lia','can','feel', “她”、“恐惧”、“为什么”、“那个”、“那个”、“地狱”、“你”、“是”、“这里”]

(仅供参考,文本文件只是我从网上找到的随机同人小说)

但是,我无法将此列表修改为按频率降序排列的列表 - 例如,该列表中有 3 个“the”,因此“the”成为列表的第一个元素。下一个元素是 'of',出现 2 次。

我尝试了几件与我的案例类似的事情,但一直显示错误(计数器,已排序)。

谁能教我如何对列表进行排序?

另外,对列表进行排序后,如何只保留一份重复的副本? (我目前的想法是使用 for 循环和索引 - 与之前的索引进行比较,如果相同则删除。)

谢谢。

【问题讨论】:

    标签: python python-3.x list sorting for-loop


    【解决方案1】:

    可以使用itertools.Counter 以不同方式进行排序:

    from collections import Counter
    
    lst = ['Hi', 'beautiful', 'creature', 'Said', 'by', 'Rothchild', 'the', 'biggest', 'enemy', 'of', 'Zun', 'Zun', 'started', 'get', 'afraid', 'of', 'him', 'As', 'her', 'best', 'friend', 'Lia', 'can', 'feel', 'her', 'fear', 'Why', 'the', 'the', 'hell', 'you', 'are', 'here']
    
    c = Counter(lst)  # mapping: {item: frequency}
    
    # now you can use the counter directly via most_common (1.)
    lst = [x for x, _ in c.most_common()]
    # or as a sort key (2.)
    lst = sorted(set(lst), key=c.get, reverse=True)
    
    # ['the', 'Zun', 'of', 'her', 'Hi', 'hell', 'him', 'friend', 'Lia', 
    #  'get', 'afraid', 'Rothchild', 'started', 'by', 'can', 'Why', 'fear', 
    #  'you', 'are', 'biggest', 'enemy', 'Said', 'beautiful', 'here', 
    #  'best', 'creature', 'As', 'feel']
    

    这些方法使用 Counter 键 (1.) 或 set 来删除重复项。

    但是,如果您希望排序相对于原始列表保持稳定(保持相同频率项目的出现顺序),您可能必须按照基于 collections.OrderedDict 的重复删除方法执行此操作:

    from collections import OrderedDict
    
    lst = sorted(OrderedDict.fromkeys(lst), key=c.get, reverse=True)
    
    # ['the', 'of', 'Zun', 'her', 'Hi', 'beautiful', 'creature', 'Said', 
    # 'by', 'Rothchild', 'biggest', 'enemy', 'started', 'get', 'afraid', 
    # 'him', 'As', 'best', 'friend', 'Lia', 'can', 'feel', 'fear', 'Why',  
    # 'hell', 'you', 'are', 'here']
    

    【讨论】:

    • 看起来我变慢了,+1 虽然我可能会使用list.sort,因为这似乎是 OP 想要的。
    • @coldspeed OP 写道他的尝试包括sorted。另外,我们在哪个list 上调用list.sort?由于尚未删除重复项,因此原始列表将导致比需要更多的工作。 sorted 的优点是可以一次性处理setDictKeys 对象,将其变成list
    • 非常感谢您的回答。我想我通过查看您编写的代码并用我的测试清楚地了解了 Counter。
    • 另外,谢谢你的orderdict,这是我不知道的东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 2015-10-18
    • 2020-10-19
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多