Eric
Eric

Reputation: 1

Finding the intersection of matching elements in multiples lists and returning the indicies

so I'm having a problem with one of my programs. I have a few lists and they are all the same length. The lists are combinations of an original list. The thing I need is the index where a specific element is repeated multiple times. For example:

a = ["x","t","y"]
b = ["t","x","y"]
c = ["t","t","y"]

I want it to turn 2.

Upvotes: 0

Views: 55

Answers (4)

dansalmo
dansalmo

Reputation: 11694

map(lambda x: x.count(x[0]) == len(x), zip(*[a, b, c])).index(True)

x.count(x[0]) == len(x) is much faster than len(set(x)) == 1

For larger sub lists > 20 elements lambda x: x == len(x)*[x[0]] is even faster:

Upvotes: 1

Drew Shafer
Drew Shafer

Reputation: 4802

one-liner:

filter(lambda x : a[x] == b[x] and a[x] == c[x], range(len(a)))

Note, that will return a list with the indexes where all elements match, so you'll actually get [2], not 2 as the result.

If you just want the integer value (not a list):

idxs = filter(lambda x : a[x] == b[x] and a[x] == c[x], range(len(a)))
result = idxs[0] if idxs else None

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

I think you're looking for something like this:

>>> a = ["x","t","y"]
>>> b = ["t","x","y"]
>>> c = ["t","t","y"]
>>> lis = [a, b, c]
>>> next( i for i,x in enumerate(zip(*lis)) if len(set(x)) == 1)
2

zip(*lis) unzips the list and you get:

>>> lis = [a, b, c]
>>> zip(*lis)
[('x', 't', 't'), ('t', 'x', 't'), ('y', 'y', 'y')]

Now we can iterate over each item of this new list and check at what index all items are equal. A set is the best way to check that.

>>> set(('y', 'y', 'y'))
set(['y'])               #length is 1

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

Something to get you started:

In [7]: for i, n in enumerate(zip(a,b,c)): print n, i
('x', 't', 't') 0
('t', 'x', 't') 1
('y', 'y', 'y') 2

Upvotes: 1

Related Questions