Ask Your Question
0

Index without multiplicities

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

CyrilleP gravatar image

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

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 +0200

rburing gravatar image

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

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 +0200

Seen: 90 times

Last updated: Dec 14 '21