Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 保留出现N次或更多次的字符串_Python_Python 2.7_Counter - Fatal编程技术网

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

Python 保留出现N次或更多次的字符串,python,python-2.7,counter,Python,Python 2.7,Counter,我有一份清单是 mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'] 我使用此列表集合中的计数器来获得结果: from collection import Counter counts = Counter(mylist) #Counter({'a': 3, 'c': 2, 'b': 2, 'd': 1}) 现在,我想将其子集,以便所有元素都出现一定次数,例如:2次或更多次-因此输出如下所示: ['a', 'b', 'c'] 这似乎应该是一项简

我有一份清单是

mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
我使用此列表集合中的计数器来获得结果:

from collection import Counter
counts = Counter(mylist)

#Counter({'a': 3, 'c': 2, 'b': 2, 'd': 1})
现在,我想将其子集,以便所有元素都出现一定次数,例如:2次或更多次-因此输出如下所示:

['a', 'b', 'c']
这似乎应该是一项简单的任务——但到目前为止,我还没有找到任何对我有帮助的东西

有人能建议找个地方看看吗?如果我采取了错误的方法,我也不会使用计数器。我应该注意到我是python新手,所以如果这是一件小事,我很抱歉

试试这个

def get_duplicatesarrval(arrval):
    dup_array = arrval[:]
    for i in set(arrval):
        dup_array.remove(i)       
    return list(set(dup_array))   



mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
print get_duplicatesarrval(mylist)
结果:

[a, b, c]

通常的方法是像@Adaman那样使用列表理解。
在2个或更多计数器的特殊情况下,还可以从另一个计数器中减去一个计数器

>>> counts = Counter(mylist) - Counter(set(mylist))
>>> counts.keys()
['a', 'c', 'b']

我认为上述答案更好,但我相信这是最简单的理解方法:

mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
newlist=[]
newlist.append(mylist[0])
for i in mylist:
    if i in newlist:
        continue
    else:
        newlist.append(i)
print newlist

>>>['a', 'b', 'c', 'd']

可能重复的功能可以使用Group by函数。只需注意-这是一个玩具示例。我需要一个项目发生的次数能够灵活地适应其他数字。我认为标题很清楚,但我将对问题进行更具体的编辑。如何指定结果需要出现的次数?以我的例子为例,如果我决定只接受出现3次或3次以上的结果,该怎么办?嗨,约翰,谢谢你的评论。对不起,我的问题不够具体。我没有意识到2个或更多是一个特例。@SamPassmore,这样做真的没有那么特别或特别快。根据我的经验,它确实在实际程序中更经常出现——计算字谜、复合数的因子等。但无论如何,列表理解是好的。
from itertools import groupby

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

res = [i for i,j in groupby(mylist) if len(list(j))>=2]

print res
['a', 'b', 'c']
mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
newlist=[]
newlist.append(mylist[0])
for i in mylist:
    if i in newlist:
        continue
    else:
        newlist.append(i)
print newlist

>>>['a', 'b', 'c', 'd']