Ask Your Question
0

Conditional list comprehension

asked 2022-03-03 10:53:42 +0200

Cyrille gravatar image

updated 2022-03-03 10:54:31 +0200

Sorry to ask so much questions at the border between Sage and Python, but I try many attempt before asking.

The following code use list comprehension

A=[[3, 2, 1, 1, 0, 0, 0], [4, 3, -1, 0, -1, 1, 0]]
B=[3,5]
AA=[v[:i] for i in B  for v in A]
AA

the result is

[[3, 2, 1], [4, 3, -1], [3, 2, 1, 1, 0], [4, 3, -1, 0, -1]]

but the result I expect is [[3, 2, 1],[4, 3, -1, 0, -1]] that is B[0] is applied to A[0] and B[1] is applied to A[1] and so on for larger exemples. Is there a way to give some conditions in list comprehension (I would like not to use loop)

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-03 11:03:24 +0200

rburing gravatar image

updated 2022-03-03 11:30:00 +0200

If you want to pair up the elements of two lists (instead of taking all combinations as you were), you can use zip (it's like a zipper):

sage: [v[:i] for v,i in zip(A,B)]
[[3, 2, 1], [4, 3, -1, 0, -1]]
edit flag offensive delete link more

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-03 10:53:42 +0200

Seen: 238 times

Last updated: Mar 03 '22