Reputation: 7337
Let's say I have a list:
Input: ids = [123, 456, 123]
I need to find the element whose frequency is 2.
Output: 123
Best way to do this in python?
Upvotes: 0
Views: 188
Reputation: 10951
This is can be done also with a built-in method, filter
to filter out only those elements who shall meet your requirement, but better do it on a set rather than list to not repeat it for the same element:
>>> ids = [123, 456, 123]
>>> s = set(ids)
>>> filter(lambda x:ids.count(x)==2, s)
>>> list(filter(lambda x:ids.count(x)==2, s)) #If Python3
[123]
Upvotes: 0
Reputation: 49320
Make a set
and count each item (or make a Counter
or defaultdict
), then find which one has a count of 2.
ids = [123, 456, 123]
freq = 2
set_ids = set(ids)
counts = {item:ids.count(item) for item in set_ids}
for item in counts:
if counts[item] == freq:
print(item)
import collections
ids = [123, 456, 123]
freq = 2
counted_ids = collections.Counter(ids)
for item in counted_ids:
if counted_ids[item] == freq:
print(item)
import collections
ids = [123, 456, 123]
freq = 2
counts = collections.defaultdict(int)
for item in ids:
counts[item] += 1
for item in counts:
if counts[item] == freq:
print(item)
Upvotes: 0
Reputation: 362557
from collections import Counter
counter = Counter(ids)
[k for k,v in counter.items() if v == 2]
Upvotes: 7