1

Edited my question to be more clear as I could not get the first answers to work.

I am trying to make a N-dimensional lookup table, from which to look up one value based on an input list of N True/False values.

For this I make an N-dimensional array, where each dimension has length 2 - one value for False (=0) and one for True (=1)

import numpy as np
import random
dims = 3
values = range(pow(2,dims))
lookup=np.reshape(values,np.tile(2,dims)) #this makes a 2x2x2x... array
condition=random.choices([True,False],k=dims) #this makes a 1d list of bools

the bools in condition should now specify the index to look up. As an example for N=3: if condition =(True,False,True), I want to get lookup[1,0,1].

Simply using

lookup[condition.astype(int)]

does not work, as numpy does not interpret the 1x3 array as index.

lookup[condition[0],condition[1],condition[2]]

works. But I havent figured out how to write this for N dimensions

5
  • 1
    answers(map(int, truth))? Since int(False) == 0 and int(True) == 1? Commented Sep 18, 2020 at 15:22
  • I don'r think i've got the question totally right, but have you tried unpacking? answer = answers(*truth)? Commented Sep 18, 2020 at 15:23
  • do you literally have a tuple? Commented Sep 18, 2020 at 15:25
  • Possible duplicate stackoverflow.com/questions/24398708/… Commented Sep 18, 2020 at 15:27
  • Some of your syntax is strange. answers([1,0,1]) doesn't make sense if answers is an ndarray. Maybe you meant answers[(1,0,1)]? Commented Sep 18, 2020 at 15:33

1 Answer 1

1

Manually converting it to a int-tuple allows the indexing you seek. Test the code below.

import numpy as np

# your example had d=3, but you may have something else.
# this is just creation of some random data...
d=3
answers = np.random.normal(size=[2] * d)
truth = tuple(np.random.choice([True, False], replace=True, size=d))

# manual conversion to int-tuple is needed, for numpy to understand that it
# is a indexing tuple.
# the box at the top of https://numpy.org/doc/stable/reference/arrays.indexing.html 
# says that tuple indexing is just like normal indexing, and in that case, we 
# need to have normal ints.
idx = tuple(int(b) for b in truth)
answer = answers[idx]
print(answer)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.