As always we need a sample data set
In [1]: from random import randint
In [2]: a = [[randint(0, 1) for _ in range(3)] for __ in range(10)]
In [3]: b = [[randint(0, 1) for _ in range(3)] for __ in range(10)]
Have a look at it
In [4]: for aa, bb in zip(a, b): print(aa, bb)
[1, 1, 0] [0, 1, 0]
[0, 0, 0] [1, 0, 0]
[1, 1, 0] [1, 1, 0]
[1, 1, 0] [0, 1, 0]
[0, 0, 0] [1, 0, 0]
[0, 0, 0] [1, 0, 1]
[1, 1, 1] [1, 1, 1]
[0, 1, 0] [1, 0, 0]
[1, 0, 1] [1, 0, 1]
[1, 1, 1] [1, 0, 0]
It seems that there are a few candidates... let's see if we can sort out the sub-lists of the first list where the first 2 elements are equal to the corresponding
elements of the corresponding sub-list in the second list.
A possible solution involves a list comprehension, using zip
to pair corresponding sub-lists and filtering according to our criterium:
In [5]: c = [aa for (aa, bb) in zip(a, b) if aa[:2]==bb[:2]]
where the comparison is done on two slices of the sub-lists, avoiding the use of the logical operator and
.
Comparing c
with the dump of a
and b
(see input cell #4)
In [6]: c
Out[6]: [[1, 1, 0], [1, 1, 1], [1, 0, 1]]
In [7]:
it seems to me that the list comprehension procedure here proposed is correct.