Tìm ra phần tử xuất hiện nhiều nhất trong List Python

How to Find the Most Common Element in a Python List

 


How to Find the Most Common Element in a Python List

In Python programming, you might encounter situations where you need to determine the most common element in a list. This is a common problem and there are several approaches to solve it.

1. Using the max() Method and key

my_list = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
most_common_element = max(set(my_list), key = my_list.count)
print("The most common element is:", most_common_element)

2. Using the collections.Counter Library

from collections import Counter
my_list = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
counter = Counter(my_list)
most_common_element = counter.most_common(1)[0][0]
print("The most common element is:", most_common_element)

3. Using the statistics.mode() Method (for Python 3.4 and above)

import statistics
my_list = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
most_common_element = statistics.mode(my_list)
print("The most common element is:", most_common_element)

Post a Comment

Mới hơn Cũ hơn