【问题标题】:Filter tokens in a list based on frequency根据频率过滤列表中的令牌
【发布时间】:2017-08-16 21:27:54
【问题描述】:

我正在处理一个包含多个不同频率标记的列表对象

from collections import Counter

s = {'book',
 'car',
 'bird',
 'cup',
 'book',
 'cup',
 'river'}

print(Counter(s))

[('book': 2), ('cup': 2), ('river': 1), ('car': 1), ('bird': 1)]

我想设置一个过滤器,只选择出现两次的标记,我在当前尝试中使用以下代码

select = [word for word in s if list(s).count(word) >= 2]
select

我认为这很简单,但我没有从“选择”中得到任何输出。我的代码出了什么问题以及如何处理?

【问题讨论】:

  • 你展示了一个set,它的每个唯一值once。请给minimal reproducible example;请注意,stack sn-ps 用于 HTML/CSS/JS,不支持 Python。

标签: python filter counter frequency


【解决方案1】:

如果 slist 而不是集合(就像您在问题中写的,但不是在示例中的代码中),您可以使用 most_common 的函数Counter 对象获取列表中的前 X 个元素:

In [67]: s = ['book',
    ...:  'car',
    ...:  'bird',
    ...:  'cup',
    ...:  'book',
    ...:  'cup',
    ...:  'river']

In [68]: s
Out[68]: ['book', 'car', 'bird', 'cup', 'book', 'cup', 'river']

In [69]: c = Counter(s)

In [70]: c.most_common(2)
Out[70]: [('book', 2), ('cup', 2)]

如果你想获得出现次数超过 Y 次的元素,你可以使用:

In [71]: [x[0] for x in c.items() if x[1] >= 2]
Out[71]: ['book', 'cup']

x[0] 是项目(来自列表),x[1] 是频率

【讨论】:

  • 这不是我想要的原因,'.most_common()' 只是对它们进行排名。
  • 您能解释一下 x[0] 和 x[1] 之间的区别吗?
  • 好的,我知道了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2018-05-17
  • 1970-01-01
  • 2021-06-23
  • 2021-09-16
  • 1970-01-01
  • 2018-01-16
相关资源
最近更新 更多