Counter When 2 Values Are Most Frequent
For example, I got a list of lists with two values which are tied in being the most frequent. Lines = the list of lists, I used: from collections import Counter most_freq = Counte
Solution 1:
This prints a list of the two most common items in the sublists:
from collections import Counter
most_common = Counter(item for sublist in lines for item in sublist).most_common(2)
print([item for item, _ in most_common])
After your comment, I think you are looking for the multimode:
from statistics import multimode
print(multimode(item for sublist in lines for item in sublist))
Solution 2:
You can use the count()
method from the list
, in order to find the total occurences of each sublist and then use the max
function to find the most frequent one:
most_common = max(lines, key=lambda e: lines.count(e))
Solution 3:
Possible adding:
most = Counter(b for sublist in lines for b in sublist).most_common(1)[0][0] # most freq'
all_freq = Counter(g for sublist in lines for g in sublist).most_common()
# prints all frequencies
how_many_times_most_appears = Counter(b for sublist in lines for b in sublist).most_common(1)[0][1] # The most frequent
for k in all_freq:
if k[1] == how_many_times_most_appears:
print(k)
# finding which value is same as the most
Post a Comment for "Counter When 2 Values Are Most Frequent"