Most frequent item in a list - Trick
Example 1:
l1 = [1, 2, 3, 1, 2, 1, 3, 2, 1, 1, 4,5]
#newList = max(l1)
#if we use the max() method then return max value 4 only but in case of a number of occurrence items in the list then we can use the key keyword and count property
newList = max(l1,key = l1.count)
if you want to optimize the above code then we can use the set
newList = max(set(l1),key = l1.count)
print(newList) # 1
Example 2:
from functools import reduce
l1 = [1, 2, 3, 1, 2, 1,1,1,1,1,1,1,1 ,3, 2, 1, 1, 4,5,5,5,5,5,5]
ar = {}
for i in l1:
if i in ar:
ar[i] += 1
else:
ar[i] = 1
print(ar)
# {1: 12, 2: 3, 3: 2, 4: 1, 5: 6}
# Use reduce to find the greatest value
gt_val = reduce(lambda x, y: x if x > y else y, ar.values())
# list comprehension
x = [key for key, val in ar.items() if val == gt_val]
print(x)
the above example is lengthy but here we can learn loop, list comprehension, reduce, lambda and many more
Example 3:
l1 = [1, 2, 3, 1, 2, 1, 3, 2, 1, 1, 4]
# let's consider
most_common_item = 0
max_count = 0
# Iterate through the list
for item in l1:
# Count the occurrences of the current item in the list
count = l1.count(item)
#print(count,'',item)
if count > max_count:
most_common_item = item # here we picked up the value
max_count = count
print("Most frequent item:", most_common_item)
Comments
Post a Comment