Reputation: 909
I am trying to find the index of elements that contain similar entries in lists of lists. Data might contained duplicated entries as well as sub-lists. For example:
list_A = [['A',[1],'a',],['B',[2],'b'],['C',[3],'c'],['D',[4],'d'],['E',[5],'e'],['A',[1],'a',]]
list_B = [['A','a'],['E','e']]
The desired output should be:
[0, 4, 5]
Upvotes: 0
Views: 57
Reputation: 288
If you eliminate the inner lists from each element in list_A, you can compare the elements directly with list_B:
list_A = [['A',[1],'a'], ['B',[2],'b'], ['C',[3],'c'], ['D',[4],'d'],
['E',[5],'e'], ['F',[6],'f']]
list_B = [['A','a'],['D','d'],['E','e']]
new_A = ([a, b] for a, _, b in list_A)
common = [i for i, x in enumerate(new_A) if x in list_B]
If you're sure that each element of list_B is uniquely present, then the following works too:
new_A = [[a, b] for a, _, b in list_A]
common = [new_A.index(x) for x in list_B]
Upvotes: 0
Reputation: 2945
If you need the number shown at index 1, you can use:
res = []
for lb in list_B:
for la in list_A:
if all([x in la for x in lb]):
res.append(la[1][0])
print sorted(res)
# OUTPUT: [1, 1, 5]
if you want the index in list_A
, you should use:
res = []
for lb in list_B:
for n, la in enumerate(list_A):
if all([x in la for x in lb]):
res.append(n)
print sorted(res)
# OUTPUT: [0, 4, 5]
Upvotes: 1
Reputation: 11083
Try this:
import itertools
list_A = [['A',[1],'a',],['B',[2],'b'],['C',[3],'c'],['D',[4],'d'],['E',[5],'e'],['A',[1],'a',]]
list_B = [['A','a'],['E','e']]
desired_output = []
for i,j in itertools.product(enumerate(list_A),list_B):
if all(k in i[1] for k in j):
desired_output.append(i[0])
output:
[0, 4, 5]
Upvotes: 1