【问题标题】:Access contents of list after applying Counter from collections module从集合模块应用计数器后访问列表的内容
【发布时间】:2016-04-16 13:16:06
【问题描述】:

我已将集合模块中的 Counter 函数应用于列表。在我这样做之后,我并不完全清楚新数据结构的内容将被描述为什么。我也不确定访问元素的首选方法是什么。

我做过类似的事情:

theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
print newList

返回:

Counter({'blue': 3, 'red': 2, 'yellow': 1})

如何访问每个元素并打印出如下内容:

blue - 3
red - 2
yellow - 1

【问题讨论】:

    标签: python list collections counter


    【解决方案1】:

    Counter 对象是字典的子类。

    Counter 是一个 dict 子类,用于计算可散列对象。它是一个无序集合,其中元素存储为字典键,其计数存储为字典值。

    您可以像访问另一个字典一样访问元素:

    >>> from collections import Counter
    >>> theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
    >>> newList = Counter(theList)
    >>> newList['blue']
    3
    

    如果你想打印键和值,你可以这样做:

    >>> for k,v in newList.items():
    ...     print(k,v)
    ...
    blue 3
    yellow 1
    red 2
    

    【讨论】:

    • 谢谢。这清楚了很多。有什么方法可以强制键值对按计数的降序打印?
    • 字典是未排序的,但你可以做一些小的跳跃来让它按排序顺序打印。有关更多信息,请参阅此答案(以及 OrderedDictionaries 通常接受的答案):stackoverflow.com/a/13990710/189134
    • 谢谢。这是一个很大的帮助。我想我通过将代码从 newList.items() 更改为 newList.most_common() 找到了解决方案。
    【解决方案2】:

    如果您希望颜色按降序计数,您可以尝试如下

    from collections import OrderedDict
    theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
    newList = Counter(theList)
    sorted_dict = OrderedDict(sorted(newList.items(), key = lambda kv : kv[1], reverse=True))
    for color in sorted_dict: 
        print (color, sorted_dict[color]) 
    

    输出:

    blue 3
    red 2
    yellow 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2018-08-01
      • 1970-01-01
      • 2011-06-28
      • 2014-08-18
      相关资源
      最近更新 更多