Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Duplicates from List After Applying Sort

I am working on code snippet to extract duplicates from a list. I have seen several implementations/solutions on this site. However, I am not getting this line correctly - syntax wise I think. After sorting, compare index(x) with index(x+1). If it is add to the set.

print(set([i for i in a if (a[i] == a[i+1]))

a = [1,2,3,2,1,5,6,5,5,5]
print(a)
print(set(sorted(a)))
# l1[i] == l1[i+1]
print(set([i for i in a if (a[i] == a[i+1]))
print(set([i for i in a if sum([1 for item in a if item == i]) > 1]))

Expected results: {1, 2, 5}

like image 861
RSSregex Avatar asked Jan 26 '23 10:01

RSSregex


1 Answers

you could use collections.Counter:

from collections import Counter

a = [1,2,3,2,1,5,6,5,5,5]
c = Counter(a)

res = [n for n, m in c.items() if m > 1]
print(res)  # [1, 2, 5]

this way you iterate once over the list and once over the counter only.

like image 95
hiro protagonist Avatar answered Feb 06 '23 07:02

hiro protagonist