问题
I am trying to find the index number in a list of elements that share the same data with elements in another list. These are my lists:
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']]
And the desired output should be:
[0,3,4]
I've tried using the set()intersection and the the index functions, but I couldn't make 'set' work with the list of lists.
回答1:
You could do the following:
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']]
set_B = list(map(set, list_B))
result = [i for i, e in enumerate(list_A) if any(b.intersection(e) for b in set_B)]
print(result)
Output
[0, 3, 4]
回答2:
If your list values don't have duplicates, you can convert everything to a set and perform subset checks inside a list comprehension.
set_A = list(map(set, list_A))
set_B = list(map(set, list_B))
# set_B = map(set, list_B) # If you intend to use and throw.
[next((i for i, a in enumerate(set_A) if a.issuperset(b)), None) for b in set_B]
# [0, 3, 4]
For now, if there is no match, next returns the default value you passed to it, in this case - None.
来源:https://stackoverflow.com/questions/53848902/find-the-index-of-supersets-for-each-sublist-in-another-list