【问题标题】:Sort list based on Counter values根据计数器值排序列表
【发布时间】:2018-04-08 23:32:36
【问题描述】:

如何根据 Counter 对象的值对 python 列表进行排序?

c = Counter({"a": 1, "b": 6, "c":19})
l = ["b", "c", "a"]

# after sorting based on counter values
l = ["c", "b", "a"]

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您可以使用 Counter 本身的 most_common 方法而不是 sorted 来获得相同的结果。

most_common = Counter({"a": 1, "b": 6, "c":19}).most_common()

列表理解:

most_common = [item[0] for item in most_common]

操作员:

import operator

most_common = list(map(operator.itemgetter(0), most_common))

结果:

['c', 'b', 'a']

【讨论】:

    【解决方案2】:

    sorted() 采用如下关键函数:

    代码:

    sorted(l, key=lambda x: -c[x])
    

    或就地为:

    l.sort(key=lambda x: -c[x])
    

    测试代码:

    from collections import Counter
    
    c = Counter({"a": 1, "b": 6, "c": 19})
    l = ["b", "c", "a"]
    
    # after sorting based on counter values
    l = ["c", "b", "a"]
    
    print(sorted(l, key=lambda x: -c[x]))
    

    结果:

    ['c', 'b', 'a']
    

    【讨论】:

    • 结果不应该反过来吗?
    猜你喜欢
    • 2018-01-01
    • 2013-10-31
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多