【问题标题】:Python: how to get sorted count of items in a list?Python:如何获取列表中项目的排序计数?
【发布时间】:2010-02-18 18:06:40
【问题描述】:

在 Python 中,我有一个项目列表,例如:

mylist = [a, a, a, a, b, b, b, d, d, d, c, c, e]

我想输出如下内容:

a (4)
b (3)
d (3)
c (2)
e (1)

如何输出列表中项目的计数和排行榜?我不太在意效率,只要任何可行的方式:)

谢谢!

【问题讨论】:

标签: python


【解决方案1】:
from collections import defaultdict

def leaders(xs, top=10):
    counts = defaultdict(int)
    for x in xs:
        counts[x] += 1
    return sorted(counts.items(), reverse=True, key=lambda tup: tup[1])[:top]

所以这个函数使用defaultdict 来计算我们列表中每个条目的数量。然后,我们获取每对条目及其计数,并根据计数按降序对其进行排序。然后我们获取 top 的条目数并将其返回。

所以现在我们可以说

>>> xs = list("jkl;fpfmklmcvuioqwerklmwqpmksdvjioh0-45mkofwk903rmiok0fmdfjsd")
>>> print leaders(xs)
[('k', 7), ('m', 7), ('f', 5), ('o', 4), ('0', 3), ('d', 3), ('i', 3), ('j', 3), ('l', 3), ('w', 3)]

【讨论】:

    【解决方案2】:

    我很惊讶没有人提到collections.Counter。假设

    import collections
    mylist = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'd', 'd', 'd', 'c', 'c', 'e']
    

    这只是一个班轮:

    print(collections.Counter(mylist).most_common())
    

    将打印:

    [('a', 4), ('b', 3), ('d', 3), ('c', 2), ('e', 1)]
    

    请注意,Counterdict 的子类,其中包含一些有用的对象计数方法。更多信息请参考the documentation

    【讨论】:

      【解决方案3】:

      两班:

      for count, elem in sorted(((mylist.count(e), e) for e in set(mylist)), reverse=True):
          print '%s (%d)' % (elem, count)
      

      【讨论】:

        猜你喜欢
        • 2015-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多