In Python, How To Compare Two Lists And Get All Indices Of Matches?
This is probably a simple question that I am just missing but I have two lists containing strings and I want to 'bounce' one, element by element, against the other returning the in
Solution 1:
Personally I'd start with:
matches = [item for item in list1 if item in list2]
Solution 2:
This does not answer the question. See my comment below.
As a start:
list(i[0] == i[1] for i in zip(list1, list2))
Solution 3:
[([int(item1 == item2) for item2 in list2], [n for n, item2 in enumerate(list2)ifitem1== item2]) for item1 in list1]
Solution 4:
I'm not sure how you want these packaged up, but this does the work:
defmatches(lst, value):
return [l == value for l in lst]
all_matches = [matches(list2, v) for l in list1]
Solution 5:
This should do what you want and it can be easily turned into a generator:
>>> [[i for i in range(len(list2)) if item1 == list2[i]]for item1 in list1]
[[3, 4], [5], []]
Here is a version with a slightly different output format:
>>>[(i, j) for i inrange(len(list1)) for j inrange(len(list2)) if list1[i] == list2[j]]
[(0, 3), (0, 4), (1, 5)]
Post a Comment for "In Python, How To Compare Two Lists And Get All Indices Of Matches?"