0

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?

Stefano Fedele
  • 6,877
  • 9
  • 29
  • 48
  • You only have got the indices. To get the values from the indices `[B[idx] for idx in idxs]` – cyborg Dec 30 '21 at 08:36
  • You can use numpy also as `import numpy as np np.array(B)[np.where(np.array(A)==2)].tolist()` – cyborg Dec 30 '21 at 08:38

2 Answers2

1

Going from end to start, using other Stack Overflow questions to improve your code:

  1. With your list of indexes, you can "fetch" the items from B according to - Access multiple elements of list knowing their index:

    C = [B[i] for i in idxs]
    
  2. Going with the indexes approach, your function could be much simplified using - How to find all occurrences of an element in a list:

    def get_index_positions(list_of_elems, element):
        return [i for i, x in enumerate(list_of_elems) if x == element]
    
  3. But really there is no need to bother with indexes at all. You can iterate through two lists in parallel and take the desired elements:

    C = [b for a, b in zip(A, B) if a == 2]
    
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

You can do it in one line using zip and a list comprehension:

A = [1, 1, 2, 2, 2, 2, 3, 4, 4]
B = [1, 4, 2, 4, 3, 1, 2, 3, 2]

[b for a, b in zip(A, B) if a == 2]

Which gives the list: [2, 4, 3, 1]

The zip part lets you go through list A and list B simultaneously. The list comprehension is simply a more elegant way of writing:

new_list = []
for a, b in zip(A, B): 
    if a == 2:
        new_list.append(b)
edvard
  • 366
  • 3
  • 8