Ask Your Question

# 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 ?

edit retag close merge delete

## 2 Answers

Sort by ยป oldest newest most voted

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)

more

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

more

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

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

Seen: 77 times

Last updated: Dec 15 '21