Ask Your Question
0

How to recover indices ?

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

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
2

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

rburing gravatar image

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

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]
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)
edit flag offensive delete link more
1

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

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

Stats

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

Seen: 176 times

Last updated: Dec 15 '21