Processing math: 100%
Ask Your Question
0

Index without multiplicities

asked 3 years ago

CyrilleP gravatar image

updated 3 years ago

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

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
0

answered 3 years ago

rburing gravatar image

updated 3 years ago

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)]
Preview: (hide)
link

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: 3 years ago

Seen: 148 times

Last updated: Dec 14 '21