What is the fastest way to filter list of tuples based on list of indices and values in Python

I have a list of sequences like: seq = [(1,2,3,4) , (1,2,4,3) (1,3,2,4) (1,3,4,2)] etc..

And another list that contains tuples (index , value) of indexes and their corresponding values like so: pos = [(3 , 4) , (1 , 2)] (at index 3, there must be a 4. At index 1, there must be a 2.)

How would i filter out the seq list in a way where i would remove all the tuples that dont have the values at their corresponding indexes in the pos list. So for example, if i had the above seq and pos variables, the result would be: [(1,2,3,4)] because it is the only sequence that has a 2 in index one and 4 in index 3.

Here is what i tried, but it doesnt work and is probably not the fastest way:

    for i in range(len(seq)):
        for j in range(len(seq)):
            for x in range(len(pos)):
                if j == pos[x][0] and seq[i][j] == pos[x][1]:
                    res.append(temp[i])



Read more here: https://stackoverflow.com/questions/64949916/what-is-the-fastest-way-to-filter-list-of-tuples-based-on-list-of-indices-and-va

Content Attribution

This content was originally published by AdamA at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: