1

Possible Duplicate:
Find and list duplicates in Python list

I have this script in Python:

routes = Trayect.objects.extra(where=['point_id IN (10,59)'])

for route in routes:
    print route

I get this response:

6 106 114 110 118 158 210 110 102 105 110 120 195 106

As you note "110" route is repeated 3 times and "106" is repeated 2 times.

How i can do for obtain only the repeated number?

I want only 110 and 106, not others. Just this:

106 110

Im not a native English speaker, and I am learning python. Thanks

***The objects in list are strings

1
  • Does order matter? Do you need 106, 110 or would 110, 106 be good too?
    – DSM
    Dec 27, 2012 at 5:12

3 Answers 3

2

This is probably the most straightforward way to do it, and also efficient even if routes has many items in it:

from collections import Counter

counts = Counter(routes)

multi_routes = [i for i in counts if counts[i] > 1]

Example usage (using numbers, but this will work for hashable type, e.g. strings are fine):

>>> from collections import Counter
>>> c = Counter([1,1,2,3,3,4,5,5,5])
>>> [i for i in c if c[i] > 1]
[1, 3, 5]
10
  • It doesnt work, maybe because is a Queryset what i have? Dec 27, 2012 at 5:30
  • No error, just a empty list [] Dec 27, 2012 at 5:34
  • Try Counter(str(i) for i in routes) then.
    – Amber
    Dec 27, 2012 at 5:35
  • @ErnestoRuizEscorcia: if routes isn't a list, then it's possible that after looping through it once (say for your print loop) there's nothing left (agotamiento). You may want to try routes = list(Trayect.objects.extra(where=['point_id IN (10,59)'])) too, or remove the print loop.
    – DSM
    Dec 27, 2012 at 5:42
  • Got this: Counter({'110': 3, '210': 1, '195': 1, '158': 1, '120': 1, '261': 1, '6': 1, '102': 1, '106': 2, '118': 1, '105': 1}) Dec 27, 2012 at 5:46
0

do you need something like this

In [1]: s = "6 106 114 110 118 158 210 110 102 105 110 120 195 106"

In [2]: l = s.split()

In [3]: [x for x in l if l.count(x) > 1]
Out[3]: ['106', '110', '110', '110', '106']

In [4]: set([x for x in l if l.count(x) > 1])
Out[4]: set(['106', '110'])
2
  • The objects in list are string, this work with strings too? Dec 27, 2012 at 5:20
  • Im using a Querylist : routes = Trayect.objects.extra(where=['point_id IN (10,59)']). Is that my problem? Dec 27, 2012 at 5:37
0
routes = [i for i in set(routes) if routes.count(i) > 1]
1
  • This will take approximately O(n^2) time for a list of n routes, which could get inefficient quickly if routes is large.
    – Amber
    Dec 27, 2012 at 5:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.