Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and leave only doubles in list python?

Tags:

python

How to find only doubles in list? My version of the algorithm

import collections
a = [1,2,3,4,5,2,4,5]
b = []

for x,y in collections.Counter(a).items():
    if y>1:
        b.append(x)

print(b)  # [2, 4, 5]

c = []
for item in a:
    if item in b:
        c.append(item)

print(c)  # [2, 4, 5, 2, 4, 5]

need find result such as c

code defects:

  1. three list (a,b,c), one collections (dict)
  2. long code

me need leave list doubles values, example. x = [1,2,2,2,3,4,5,6,6,7‌​], need [2,2,2,6,6] not [2,6]

like image 787
Igor Avatar asked Aug 16 '16 07:08

Igor


1 Answers

from collections import Counter

a = [1, 2, 3, 4, 5, 2, 4, 5]
counts = Counter(a)
print([num for num in a if counts[num] > 1])
like image 129
Karin Avatar answered Sep 28 '22 06:09

Karin