python - 保留出现 N 次或更多次的字符串

标签 python python-2.7 counter

我有一个列表是

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

我使用了这个列表中集合中的 Counter 来得到结果:

from collection import Counter
counts = Counter(mylist)

#Counter({'a': 3, 'c': 2, 'b': 2, 'd': 1})

现在我想对其进行子集化,以便我拥有出现一定次数的所有元素,例如:2 次或更多次 - 因此输出如下所示:

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

这看起来应该是一项简单的任务 - 但到目前为止我还没有找到任何对我有帮助的东西。

谁能推荐个地方看看?如果我采取了错误的方法,我也不喜欢使用 Counter。我应该注意我是 python 的新手,所以如果这是微不足道的,我深表歉意。

最佳答案

[s for s, c in counts.iteritems() if c >= 2]
# => ['a', 'c', 'b']

关于python - 保留出现 N 次或更多次的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30837335/

相关文章:

python - 递归后重置计数器

python - TypeError at/accounts/register/__init__() 得到意外的关键字参数 'instance'

python - 如何使用 Python 获取某人的 Facebook ID?

python - 如何改进这个 find() 函数(或类似函数)

Python 从值列表创建日期时间对象

c - i++ 不在 while 循环内工作

php - 将 div.container 包裹在 foreach 中

python - 我们可以在模块中使用完全限定标识符而不导入模块吗?

python - 如何在装饰器中注册它装饰的所有功能?

Python处理socket.error : [Errno 104] Connection reset by peer