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
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.
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 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.
Personally I'd start with:
matches = [item for item in list1 if item in list2]
This does not answer the question. See my comment below.
As a start:
list(i[0] == i[1] for i in zip(list1, list2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With