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.Wed, 15 Dec 2021 16:33:03 +0100How to recover indices ?https://ask.sagemath.org/question/60271/how-to-recover-indices/ Suppose I have indexed variables as
z=[var(f'p_{k}{l}') for k in range(2) for l in range(4)]
I can easily print `z[6]`. But what I want to use is it's two indices. How can I recover them ?
Wed, 15 Dec 2021 11:29:05 +0100https://ask.sagemath.org/question/60271/how-to-recover-indices/Answer by Max Alekseyev for <p>Suppose I have indexed variables as</p>
<pre><code>z=[var(f'p_{k}{l}') for k in range(2) for l in range(4)]
</code></pre>
<p>I can easily print <code>z[6]</code>. But what I want to use is it's two indices. How can I recover them ?</p>
https://ask.sagemath.org/question/60271/how-to-recover-indices/?answer=60281#post-id-60281You can use list of lists:
z=[ [var(f'p_{k}{l}') for l in range(4)] for k in range(2)]
and access its elements like `z[1][3]`.Wed, 15 Dec 2021 16:33:03 +0100https://ask.sagemath.org/question/60271/how-to-recover-indices/?answer=60281#post-id-60281Answer by rburing for <p>Suppose I have indexed variables as</p>
<pre><code>z=[var(f'p_{k}{l}') for k in range(2) for l in range(4)]
</code></pre>
<p>I can easily print <code>z[6]</code>. But what I want to use is it's two indices. How can I recover them ?</p>
https://ask.sagemath.org/question/60271/how-to-recover-indices/?answer=60273#post-id-60273I would use a different data structure, namely a dictionary:
p = {(k,l) : var(f'p_{k}{l}') for k in range(2) for l in range(4)}
Then you can do:
sage: p[0,0]
p_00
sage: p[1,2]
p_12
And if you want, you can define your flattened list `z` based on this dictionary:
z = [p[k,l] for k in range(2) for l in range(4)]
And to go from a variable to a tuple of indices you can define an "inverse" dictionary:
p_inverse = {v:k for k,v in p.items()}
Indeed:
sage: p_inverse[p[1,2]]
(1,2)Wed, 15 Dec 2021 13:27:28 +0100https://ask.sagemath.org/question/60271/how-to-recover-indices/?answer=60273#post-id-60273