Search code examples
pythonlistiteration

Find element in list n times Python


Given are

a = [1, 4, 2, 5]

b = [[[0, 1]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 6]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 4]],
     [[0, 5]], [[0, 6]], [[0, 4]], [[0, 2]], [[0, 2]], [[0, 4]], [[0, 4]], [[0, 5]], [[0, 5]], [[0, 5]], [[0, 1]],
     [[0, 5]], [[0, 1]], [[0, 1]]]

My goal is to iterate over the list a and to identify (print) those elements in b which have the element of a as element at index 1. The whole thing becomes difficult by the fact that this process may occur exactly three times for each element. After that, the next index in a is to be selected. In concrete terms, the whole thing should look like this at the end:

[[0, 1]]
[[0, 1]]
[[0, 1]]
[[0, 4]]
[[0, 4]]
[[0, 4]]
[[0, 2]]
[[0, 2]]
[[0, 2]]
[[0, 5]]
[[0, 5]]
[[0, 5]]

All elements in b beyond that are to be ignored, even and especially if they occur more than three times.

I have already tried various techniques ( random, while loop, etc.), racked my brain and searched this forum, but I am stuck.

It doesn't matter which elements are selected in b, the main thing is that there are three for each element in a.


Solution

  • If you want to make it easier, you can simply follow the steps below:

    a = [1, 4, 2, 5]
    
    b = [[[0, 1]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 6]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 4]],
         [[0, 5]], [[0, 6]], [[0, 4]], [[0, 2]], [[0, 2]], [[0, 4]], [[0, 4]], [[0, 5]], [[0, 5]], [[0, 5]], [[0, 1]],
         [[0, 5]], [[0, 1]], [[0, 1]]]
    
    for val_a in a:
        counter = 0
        for val_b in b:
           if val_a == val_b[0][1]:
               counter += 1
               if counter < 4:
                    print(val_b)
    

    I hope I could help! :D