Пошук повторюваних елементів у списку Python

20.10.2022 0 By svvas

Маємо на вході список, потрібно знайти всі елементи, які повторюються

[10, 10, 23, 10, 123, 66, 78, 123] 

Тобто на виході потрібно отримати:

{10: 3, 123: 2}

Перший спосіб:

A = [10, 10, 23, 10, 123, 66, 78, 123]
counter = {}

for elem in A:
    counter[elem] = counter.get(elem, 0) + 1

doubles = {element: count for element, count in counter.items() if count > 1}

print(doubles)

Другий спосіб:

from collections import Counter
counter = Counter(A)

Третій спосіб:

from collections import defaultdict
counter = defaultdict(int)
for elem in A:
    counter[elem] += 1

Comments

comments