I have a couple of lists such as the following ones
A = [1, 1, 2, 2, 2, 2, 3, 4, 4]
B = [1, 4, 2, 4, 3, 1, 2, 3, 2]
in list A all and only the positions 2, 3, 4, and 5 contain the number 2. What I am looking for are the B values associated with these indexes, which is
C = [2, 4, 3, 1]
Could you help me with this issue, please?
The way I figured out uses the following function
#https://thispointer.com/python-how-to-find-all-indexes-of-an-item-in-a-list/
def get_index_positions(list_of_elems, element):
''' Returns the indexes of all occurrences of give element in
the list- listOfElements '''
index_pos_list = []
index_pos = 0
while True:
try:
# Search for item in list from indexPos to the end of list
index_pos = list_of_elems.index(element, index_pos)
# Add the index position in list
index_pos_list.append(index_pos)
index_pos += 1
except ValueError as e:
break
return index_pos_list
which provides me all the indexes of A list containing the value 2, as follows
idxs = get_index_positions(A, 2)
than I get
idxs = [2, 3, 4, 5]
Which makes me feel I am nearly there. However, I believe I need something smart and efficient to tell python to take all and only the B values associated with the idxs indexes
Anyone can suggest me anything?