【问题标题】:How to use Counter in python without showing numbers如何在python中使用计数器而不显示数字
【发布时间】:2021-06-05 16:05:30
【问题描述】:

我对 python 的 Counter 库没什么问题。这是一个例子:

from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))

它的输出:

Counter({'x': 4, 'y': 2, 'z': 2})

我的问题是如何在没有重复次数的情况下接收输出?

我想要得到的是:

Counter('x', 'y', 'z')

【问题讨论】:

  • 如果您不想计数,为什么还要使用计数器?
  • 那我应该用什么?我想要从最常见元素到最稀有元素的排序输出。
  • “我想要从最常见的元素到最稀有的元素的排序输出” - 看,这是您应该首先告诉我们的重要信息。这排除了像集合这样的选项,这似乎是问题中的明显选择。
  • 为什么不改用set

标签: python list counter python-collections


【解决方案1】:

您需要从most_common()中提取密钥:

from collections import Counter
list1 = ['x', 'y', 'z', 'x', 'x', 'x', 'y', 'z']

print(Counter(list1).most_common())  # ordered key/value pairs
print(Counter(list1).keys())  # keys not ordered!

keys = [k for k, value in Counter(list1).most_common()]
print(keys)  # keys in sorted order!

输出:

[('x', 4), ('y', 2), ('z', 2)]
['y', 'x', 'z']
['x', 'y', 'z']

【讨论】:

    【解决方案2】:

    如果你只想要一个列表的不同元素,你可以把它转换成一个集合。

    话虽如此,您也可以使用 keys 方法访问 Counter 字典的键以获得类似的结果。

    【讨论】:

      【解决方案3】:

      如果我们把 Counter 的输出看成一个字典,我们可以通过只获取字典的键来只获取字符串:

      from collections import Counter
      list1 = ['x','y','z','x','x','x','y','z']
      values = Counter(list1).keys()
      print(values)
      

      【讨论】:

        猜你喜欢
        • 2012-10-12
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2016-07-16
        • 1970-01-01
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        相关资源
        最近更新 更多