How to select a serie of sublists according to an other list

One more time this is certainly the result of my lack of expertise in programming but I encounter the following problem.

I have a list of lists

A=[[3, 2, 1, 1, 0, 0, 0, 5],   [4, 3, -1, 0, -1, 1, 0, 4],   [1, 2, 2, 0, 0, 0, 1, 2]]


and an other list

B=[3,5]


What I want is to select a sublist of the list A according to the following criterion : keep the sublist A[i] if A[i][j]==1 for j in B

edit retag close merge delete

1

This is a bit ambiguous, as revealed by the proposed answer: do you mean "for all j in B" or "for some j in B"?

( 2022-03-03 18:44:11 +0200 )edit

Sort by ยป oldest newest most voted

It's quite straightforward:

[a for a in A if all(a[j]==1 for j in B)]

more

On my computer the effect of your proposal is an empty list when it should be [[3, 2, 1, 1, 0, 0, 0, 5], [4, 3, -1, 0, -1, 1, 0, 4]]

( 2022-03-03 08:20:15 +0200 )edit

It seems that you search for the sublists of A containing an element of B. If it is effectively the case, then try

sage: [a for a in A if any(aj in B for aj in a)]
[[3, 2, 1, 1, 0, 0, 0, 5], [4, 3, -1, 0, -1, 1, 0, 4]]

( 2022-03-03 09:04:29 +0200 )edit

My answer solves the problem you posed. If the answer is different from expected, then you posed the problem incorrectly.

( 2022-03-03 18:05:35 +0200 )edit