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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With