Ask Your Question
1

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

asked 2022-03-02 21:55:00 +0200

Cyrille gravatar image

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 flag offensive close merge delete

Comments

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"?

John Palmieri gravatar imageJohn Palmieri ( 2022-03-03 18:44:11 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-03 02:47:49 +0200

Max Alekseyev gravatar image

It's quite straightforward:

[a for a in A if all(a[j]==1 for j in B)]
edit flag offensive delete link more

Comments

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]]

Cyrille gravatar imageCyrille ( 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]]
David Coudert gravatar imageDavid Coudert ( 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.

Max Alekseyev gravatar imageMax Alekseyev ( 2022-03-03 18:05:35 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-03-02 21:55:00 +0200

Seen: 223 times

Last updated: Mar 03 '22