How to remove duplicates and count elements in Python?
You can utilize the Counter class to achieve deduplication and counting of elements. The Counter class is a built-in class in the collections module that can be used to count the number of hashable objects.
Below is a sample code demonstrating how to use the Counter class to remove duplicates and count elements in a list.
from collections import Counter
# 定义一个列表
my_list = [1, 2, 3, 4, 2, 3, 4, 5, 6, 1, 2, 3]
# 使用Counter类对列表中的元素进行计数
count_dict = Counter(my_list)
# 打印去重后的元素和计数
for element, count in count_dict.items():
print(f"{element}: {count}")
When executing the code above, the output will be:
1: 2
2: 3
3: 3
4: 2
5: 1
6: 1
After deduplication, the unique elements and their counts are printed out separately.