Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to compare two lists and get all indices of matches?

Tags:

python

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 index of the matches. I expect there to be multiple matches and want all of the indices. 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 would iterate through list1 comparing to list2 and output:
[0,0,0,1,1,0] , [3,4] or etc for the first iteration
[0,0,0,0,0,1] , [6] for second
and [0,0,0,0,0,0] or [] for third

EDIT: Sorry for any confusion. I would like to get the results in a way such that I can then use them like this- I have a third list lets call list3 and I would like to get the values from that list in the indices that are outputed. ie list3[previousindexoutput]=list of cooresponding values

like image 287
Kosig Avatar asked Feb 08 '11 19:02

Kosig


People also ask

Can you compare indexes in Python?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do you compare values in two lists in Python?

The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.

How do you match index in Python?

How to Find the Index of a List Element in Python. You can use the index() method to find the index of the first element that matches with a given search object. The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.


2 Answers

Personally I'd start with:

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

like image 119
porgarmingduod Avatar answered Sep 29 '22 22:09

porgarmingduod


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

As a start:

list(i[0] == i[1] for i in zip(list1, list2))
like image 24
Dennis Benzinger Avatar answered Sep 29 '22 20:09

Dennis Benzinger