python – How to determine the index of elements from one list to another

Question:

I work with python 2.7 . Considering the following:

S_names=["A", "B", "C", "D", "E", "F", "G"]
S_values=[1,3,4,2,5,8,10]
other=["Z","W","B","S","A","E","X","T","D","G","L","C","F"]

I need to find in what position of other the elements of S_names are located. To get the list of indices of the elements of S_names in other , resulting in the Result list:

Result=[4,2,11,8,5,12,9] 

I tried working with dictionaries by doing the following:

def indicesDeElementoNaLista_s(elementoProcurado, lista):
    return [i for (i, elemento) in lista if elemento == elementoProcurado]

def elementosNasPosicoes_s(lista, posicoes):
    return [lista[i] for i in posicoes]

carg={}
for elemento in S_names:
    posicoes=indicesDeElementoNaLista_s(elemento,other)
    elementosCorrespondentes=elementosNasPosicoes_s(S_values,posicoes)
    cargas_sub[elemento]=elementosCorrespondentes_s

But I got several errors and I don't understand what is wrong… How can I get around this situation?

Answer:

To get the result you want, you can do as follows:

>>> S_names = ["A", "B", "C", "D", "E", "F", "G"]
>>> S_values =[1, 3, 4, 2, 5, 8, 10]
>>> other = ["Z", "W", "B", "S", "A", "E", "X", "T", "D", "G", "L", "C", "F"]
>>> 
>>> Result = [other.index(i) for i in S_names if i in other]
>>> print(Result)
[4, 2, 11, 8, 5, 12, 9]

However, this only relates the S_names and other lists. Looking at the rest of your code, I imagine you want a dictionary with the name and position of the items that repeat in the 'other' list and the positions that repeat in the S_values ​​list. If so, you can do it like this:

>>> posicoes = [other.index(i) for i in S_names if i in other]
>>> print(posicoes)
[4, 2, 11, 8, 5, 12, 9]
>>>
>>> elementosCorrespondentes = [S_values[i] for i in range(len(S_values)) if S_values[i] == posicoes[i]]
>>> print(elementosCorrespondentes)
[5]
>>>
>>> carg = {S_names[i]:i for i in elementosCorrespondentes}
>>> print(carg)
{'F': 5}
Scroll to Top