Reputation: 23
I am trying to make a cartesian product from a list of arrays but it keeps giving me a TypeError: iteration over a 0-d array
I have a list which looks like:
print(a)
>>>[array([1., 2.]), array([3., 4.]), array(1400.)]
Now, when I try to do:
b=list(itertools.product(*a))
>>>TypeError: iteration over a 0-d array
What am I missing?
Upvotes: 2
Views: 176
Reputation: 39052
As explained by @user2357112 in the comments, you currently have the last element as a 0 dimensional array. If you check the length of it, you will get TypeError: len() of unsized object
. To get your solution working, you need to enclose the element in the last array using []
to be able to use the product
import itertools
a = [np.array([1., 2.]), np.array([3., 4.]), np.array([1400.])]
b = list(itertools.product(*a))
#[(1.0, 3.0, 1400.0),
# (1.0, 4.0, 1400.0),
# (2.0, 3.0, 1400.0),
# (2.0, 4.0, 1400.0)]
Edit answering second question on request:
import itertools
dict1 = {'wdth_i': ['1', '2'], 'wdth_p': ['3', '4'], 'mu': '1400'}
a = []
for i in dict1.values():
if isinstance(i, list):
a.append(i)
else:
a.append([i])
f = list(itertools.product(*a))
# [('1', '3', '1400'),
# ('1', '4', '1400'),
# ('2', '3', '1400'),
# ('2', '4', '1400')]
Upvotes: 2