-1

Suppose I've a list here:

list = ['cat', 'dog', 'wolf', 'cat', 'wolf', 'cat', 'sheep', 'sheep']

I want to fetch only those words from which are having common frequency greater than 1.

Resultant list should be:

['cat', 'wolf', 'sheep']

Can anyone help me with this?

TR9
  • 23
  • 4

2 Answers2

2

You can use collections.Counter to count the number of repetitions, then use a list comprehension to keep only those with a count greater than 1.

>>> from collections import Counter
>>> words = ['cat', 'dog', 'wolf', 'cat', 'wolf', 'cat', 'sheep', 'sheep']
>>> c = Counter(words)
>>> [k for k, v in c.items() if v > 1]
['cat', 'wolf', 'sheep']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1
list = ['cat', 'dog', 'wolf', 'cat', 'wolf', 'cat']

items_map = {}
for item in list:
    if item not in items_map.keys():
        items_map[item] = 1
    else:
        items_map[item] += 1

result = []

for key in items_map.keys():
    if items_map[key] > 1:
        result.append(key)

print(result)
Vizzyy
  • 522
  • 3
  • 11