0

I have a list of tuples (of integers), which is quite long to loop over. I also have a numpy array. I want to get the element given by each tuple in the list, without having to loop over the list. Something like this:

mySum = np.sum(myArray(myList))

which of course doesn't work. Is there a way for me to make this happen? The list looks something like this: myList = [(1,2,2),(0,0,2),...,(100,122,200)].

myArray is a 3d numpy array.

5
  • Is myArray a numpy array with three dimensions? Commented Aug 6, 2015 at 23:36
  • How does myArray look like? Commented Aug 6, 2015 at 23:40
  • @TillHoffmann Sorry, I forgot, see the edit. Commented Aug 6, 2015 at 23:44
  • @ozgur Sorry, I forgot, see the edit. Commented Aug 6, 2015 at 23:44
  • Thanks for the clarification. Commented Aug 6, 2015 at 23:45

1 Answer 1

1

You can extract the indices for each dimension and then slice the numpy array (assuming myArray is an array with three dimensions):

# Define the indices
myList = [(1,2,2), (0,0,2), (100,122,200), (3, 4, 5)]
# Define the array (just random numbers)
myArray = np.random.uniform(size=(101, 201, 201))
# Extract the indices
a, b, c = np.transpose(myList)
# Slice the numpy array and sum
mySum = np.sum(myArray[a, b, c])
Sign up to request clarification or add additional context in comments.

2 Comments

What does transpose do exactly?
Transpose changes myList from an n-by-three array to a three-by-n array. Rather than a long list of three-tuples you end up with three lists of integers. You can find more information here: docs.scipy.org/doc/numpy/reference/generated/… and here en.wikipedia.org/wiki/Transpose

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.