2

I have this list:

a = [ np.array([ 1, 2]), np.array([0])]

I want to iterate:

x = np.array([t[i] for i, t in enumerate(a)])

but since np.array([0]) has only one element, it will throw an error.

So, I thought to fill the np.array([0]) with another one zero , and then

a = [ np.array([ 1,  2]), np.array([0,0])]
x = np.array([t[i] for i, t in enumerate(a)])
print(x)

[1 0]

So, I am finding the biggest length in the list:

temp = []
for i in a:
    temp.append(len(i))

themax = max(temp)  

which is 2. (the np.array([1, 2]).

Now, I must somehow fill the other subelements with zeros..

Note, that I will always have the zero np.array([0]) which causes the problem.

2
  • Maybe np.empty() is what you're looking for? Commented Mar 7, 2017 at 9:00
  • @Jan:No, I will have zeros in the list and i have to keep them. Commented Mar 7, 2017 at 9:02

1 Answer 1

1

The easiest way would be to change your list comprehension to give a zero instead of an array element in the case of an array being too small:

x = np.asarray([(t[i] if i < t.shape[0] else 0.) for i, t in enumerate(a)])

This is more efficient as you don't have to expand all arrays with zeros.

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.