Ask Your Question

How to recover indices ?

asked 2021-12-15 11:29:05 +0200

CyrilleP gravatar image

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 ?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2021-12-15 13:27:28 +0200

rburing gravatar image

updated 2021-12-15 13:32:20 +0200

I 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]
sage: p[1,2]

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()}


sage: p_inverse[p[1,2]]
edit flag offensive delete link more

answered 2021-12-15 16:33:03 +0200

Max Alekseyev gravatar image

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

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


Asked: 2021-12-15 11:29:05 +0200

Seen: 117 times

Last updated: Dec 15 '21