Reputation: 990
I have two lists:
1. ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'f']
2. ['c', 'd']
and I'd like to get indexes of the intersection a, b:
3. [[2, 3], [5, 6]]
How would you do that with Python?
Also these inputs:
1. ['263', '9', '470', '370', '576', '770', '800', '203', '62', '370', '576', '370', '25', '770', '484', '61', '914', '301', '550', '770', '484', '1276', '108']
2. ['62', '370', '576']
should give:
3. [[8, 9, 10]]
Upvotes: 1
Views: 108
Reputation: 88
For your given example this will work
>>> x = ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'f']
>>> y = ['c', 'd']
>>> z = [[i for i, xi in enumerate(x) if xi == yi] for yi in y]
>>> z
[[2, 5], [3, 6]]
>>> zip(*z)
[(2, 3), (5, 6)]
It makes uses of the enumerate function to get the indices of x
along with the values and then transposes the result using zip(*z)
. You can convert from tuples to lists afterward.
Edit: transposed result.
Upvotes: 1
Reputation: 123708
One way would be:
>>> l1 = ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'f']
>>> l2 = ['c', 'd']
>>> [range(i,i+len(l2)) for i in xrange(len(l1)-len(l2)+1) if l2 == l1[i:i+len(l2)]]
[[2, 3], [5, 6]]
>>>
Upvotes: 2
Reputation: 3640
Maybe a little too much code, but it works.
def indexes(list, element):
c = 0
output = []
for e in list:
if e == element:
output.append(c)
c += 1
return output
a = ['a', 'b', 'c', 'd', 'a']
b = ['a', 'd']
output = []
for el in b:
output.append(indexes(a, el))
print(output)
Upvotes: 0