In Python, how do I compare two lists and get all the match indices?

This is probably a simple question that I just skip, but I have two lists containing strings, and I want to β€œbounce” one, element by element, and the other back. I expect that there will be many matches and you will want all the indexes. I know that list.index () gets the first, and you can easily get the last. For example:

list1 = ['AS144','401M','31TP01'] list2 = ['HDE342','114','M9553','AS144','AS144','401M'] 

Then I will iterate over list1 compared to list2 and output:
[0,0,0,1,1,0] , [3,4] or the like. for the first iteration [0,0,0,0,0,1] , [6] for the second and [0,0,0,0,0,0] or [] for the third

EDIT: Sorry for any confusion. I would like to get the results in such a way that I can use them as follows: I have a third list that allows list3 to be called, and I would like to get the values ​​from this list in the output indexes. those. list3[previousindexoutput]=list of cooresponding values

+7
source share
7 answers
 [([int(item1 == item2) for item2 in list2], [n for n, item2 in enumerate(list2) if item1 == item2]) for item1 in list1] 
+1
source

Personally, I would start with:

matches = [item for item in list1 if item in list2]

+8
source

This does not answer the question. See my comment below.

At the beginning:

 list(i[0] == i[1] for i in zip(list1, list2)) 
+3
source

I'm not sure how you want them to be packaged, but this does the job:

 def matches(lst, value): return [l == value for l in lst] all_matches = [matches(list2, v) for l in list1] 
+1
source
 def findInstances(list1, list2): """For each item in list1, return a list of offsets to its occurences in list2 """ for i in list1: yield [pos for pos,j in enumerate(list2) if i==j] list1 = ['AS144','401M','31TP01'] list2 = ['HDE342','114','M9553','AS144','AS144','401M'] res = list(findInstances(list1, list2)) 

leads to

 [[3, 4], [5], []] 
+1
source

This will give a list of lists with True / False values ​​instead of 1/0:

 matches = [ [ list1[i] == list2[j] for j in range(0, len(list2)) ] for i in range(0, len(list1)) ] 

Edit: if you use 2.5 or later, this should give 1 and 0:

 matches = [ [ 1 if list1[i] == list2[j] else 0 for j in range(0, len(list2)) ] for i in range(0, len(list1)) ] 
0
source

This should do what you want, and it can easily be 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 in range(len(list1)) for j in range(len(list2)) if list1[i] == list2[j]] [(0, 3), (0, 4), (1, 5)] 
0
source

All Articles