4

I have three lists.

a = [1, 2, 3, 4, 5]  
b = [6, 7, 8, 9, 10]  
c = [11, 12 , 13, 14, 15]  

I combine them and make one list of tuples using list comprehension

combine_list = [(a1, b1, c1) for a1 in a for b1 in b for c1 in c]

This combine list has 5*5*5 = 125 elements.

Now I want to convert this combine_list into a numpy array with shape (5, 5, 5). So, I use the following code:

import numpy as np
combine_array = np.asarray(combine_list).reshape(5, 5, 5)

This gives me an error:

ValueError: total size of new array must be unchanged

But, when I try to reshape list of single 125 numbers (no tuple elements) to a numpy array, no such error occurs.

Any help on how to reshape list of tuples to a numpy array ?

3
  • What does np.asarray(combine_list) produce? (shape and dtype) Commented Oct 14, 2015 at 1:26
  • You don't have 125 elements, but 125 * 3 = 375 Commented Oct 14, 2015 at 1:26
  • @JBernardo : Thanks for pointing out the error. Commented Oct 14, 2015 at 23:11

2 Answers 2

2

Not sure if this is what you want, but you can use multi-dimensional list comprehension.

combine_list = [[[ (i, j, k) for k in c] for j in b] for i in a]
combine_array = np.asarray(combine_list)
Sign up to request clarification or add additional context in comments.

Comments

1

If you really need the 3 ints in a 5x5x5 then you need a dtype of 3 ints. Using itertools.product to combine the lists:

>>> import itertools
>>> np.array(list(itertools.product(a,b,c)), dtype='int8,int8,int8').reshape(5,5,5)

Alternatively, just include the 3 elements in the reshape:

>>> np.array(list(itertools.product(a,b,c))).reshape(5,5,5,3)

1 Comment

This also works, but the answer by @jethrocao was easy and simple enough

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.