Keep strings that occur N times or more

82 views Asked by At

I have a list that is

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

And I used Counter from collections on this list to get the result:

from collection import Counter
counts = Counter(mylist)

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

Now I want to subset this so that I have all elements that occur some number of times, for example: 2 times or more - so that the output looks like this:

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

This seems like it should be a simple task - but I have not found anything that has helped me so far.

Can anyone suggest somewhere to look? I am also not attached to using Counter if I have taken the wrong approach. I should note I am new to python so I apologise if this is trivial.

5

There are 5 answers

0
Amadan On BEST ANSWER
[s for s, c in counts.iteritems() if c >= 2]
# => ['a', 'c', 'b']
0
Bhoomika Sheth On

I think above mentioned answers are better, but I believe this is the simplest method to understand:

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']
1
Deenadhayalan Manoharan On

Try this...

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)

Result:

[a, b, c]
2
John La Rooy On

The usual way would be to use a list comprehension as @Adaman does.
In the special case of 2 or more, you can also subtract one Counter from another

>>> counts = Counter(mylist) - Counter(set(mylist))
>>> counts.keys()
['a', 'c', 'b']
0
rajeshv90 On
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']