ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 14 Dec 2021 13:54:53 +0100Index without multiplicitieshttps://ask.sagemath.org/question/60254/index-without-multiplicities/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)]`.Tue, 14 Dec 2021 12:02:03 +0100https://ask.sagemath.org/question/60254/index-without-multiplicities/Answer by rburing for <p>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 ?</p>
<p>So</p>
<pre><code>z=[5,0,5,0,10,13,14,]
zz=[(z.index(v),v) for v in z if v!=0]
show(zz)
</code></pre>
<p>returns <code>[(0, 5), (0, 5), (4, 10), (5, 13), (6, 14)]</code> when I want <code>[(0, 5), (2, 5), (4, 10), (5, 13), (6, 14)]</code>.</p>
https://ask.sagemath.org/question/60254/index-without-multiplicities/?answer=60257#post-id-60257It'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)]Tue, 14 Dec 2021 13:54:53 +0100https://ask.sagemath.org/question/60254/index-without-multiplicities/?answer=60257#post-id-60257