Ask Your Question
0

Index without multiplicities

asked 2021-12-14 12:02:03 +0100

CyrilleP gravatar image

updated 2021-12-14 12:03:31 +0100

I want really the vector zz. Unfortunatelly as 5 is present with multiplicity 2 the only index for 5 is 0. I want also 2. How to obtain the desired return ?

So

z=[5,0,5,0,10,13,14,] 
zz=[(z.index(v),v) for v in z if v!=0]
show(zz)

returns [(0, 5), (0, 5), (4, 10), (5, 13), (6, 14)] when I want [(0, 5), (2, 5), (4, 10), (5, 13), (6, 14)].

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-12-14 13:54:53 +0100

rburing gravatar image

updated 2021-12-14 17:12:20 +0100

slelievre gravatar image

It's easier to iterate over the indices (rather than the values) in the first place:

sage: zz = [(k, z[k]) for k in range(len(z)) if z[k] != 0]
sage: zz
[(0, 5), (2, 5), (4, 10), (5, 13), (6, 14)]

Or a bit cleaner, using enumerate:

sage: zz = [(k, v) for k, v in enumerate(z) if v != 0]
sage: zz
[(0, 5), (2, 5), (4, 10), (5, 13), (6, 14)]
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: 2021-12-14 12:02:03 +0100

Seen: 136 times

Last updated: Dec 14 '21