Take the 2-minute tour ×

I'm coming back to programming after years off and am having trouble wrapping my head around this problem. The user is defining the Classification set amount but the RasterValue is list is of length N

Example: ClassificationSet = (1, 2, 3, 4, 5, 6) #defined by user
RasterVal = () #length = N

I store items into RasterVal using ClassificationSet as an index: RasterVal(ClassificationSet).add(Imported Value)

RasterVal(1) = 22,23,24,25,23,23,22
RasterVal(2) = 22,30,31,32,30,30
RasterVal(3) = 31

which is: RasterVal([],[22,23,24,25,23,23,22], [22,30,31,32,30,30], [31])

I want to list values that are repeated but only if they are repeated in different sets, not the same one.

Output should be: RepeatSet = 22, 31

Thank you very much for any help. I've been able to compare the sets but it lists repeated values even if they appear in the same set list.

share|improve this question
You could try using a set and a Counter together to get it done. –  lukecampbell May 11 '12 at 19:21
Related: stackoverflow.com/questions/2116286/… –  ChristopheD May 11 '12 at 19:23
add comment

3 Answers

up vote 4 down vote accepted

@lukecampbell is right:

>>> lsts = [[22,23,24,25,23,23,22],[22,30,31,32,30,30],[31]]
>>> from collections import Counter
>>> c = Counter(x for lst in lsts for x in set(lst))
>>> [x for x,y in c.items() if y > 1]
[22, 31]

The runtime of this algorithm is linear, rather than quadratic in the number of sets.

share|improve this answer
add comment
RasterVal = [[22,23,24,25,23,23,22],[22,30,31,32,30,30],[31]]

from itertools import combinations
out = set()
for a,b in combinations(RasterVal,2):
    out = out|(set(a)&set(b))

print out
set([22, 31])
share|improve this answer
add comment
#-- Your initial data...
rasterVals = [

#-- This will be a set, which holds only distinct values.
repeated = set( )

#-- We set up a classic inner-outer loop to iterate over all 
#-- pairs of lists in your given data.  (Note, there are better ways
#-- of doing this in Python, but this is the easiest to read and understand)
for a in rasterVals:
    #-- First, we'll make a set from the first element.
    #-- Since sets only hold distinct values, any repeated numbers
    #-- in the sequence will be ignored.
    s = set(a)

    for b in rasterVals:
        #-- Test that we are not comparing a sequence to itself.
        if (a is not b):
            #-- Make a set for the inner loop. (again, only distinct numbers...)
            t = set(b)

            #-- Get the intersection of s and t, answering with only those elements
            #-- that are in both s and t.
            intersecting = (s & t)

            #-- We update our set of (inter-sequence) repeated elements.

#-- Show the results.
print repeated
share|improve this answer
add comment

Your Answer


