dontdeimos
dontdeimos

Reputation: 19

Saving to an empty array of arrays from nested for-loop

I have an array of arrays filled with zeros, so this is the shape I want for the result.

I'm having trouble saving the nested for-loop to this array of arrays. In other words, I want to replace all of the zeros with what the last line calculates.

percent = []
for i in range(len(F300)):
    percent.append(np.zeros(lengths[i]))

for i in range(0,len(Name)):
    for j in range(0,lengths[i]):
        percent[i][j]=(j+1)/lengths[i]

The last line only saves the last j value for each i.

I'm getting:

percent = [[0,0,1],[0,1],[0,0,0,1]]

but I want:

percent = [[.3,.6,1],[.5,1],[.25,.5,75,1]]

Upvotes: 1

Views: 391

Answers (1)

Erick Shepherd
Erick Shepherd

Reputation: 1443

The problem with this code is that because it's in Python 2.7, the / operator is performing "classic" division. There are a couple different approaches to solve this in Python 2.7. One approach is to convert the numbers being divided into floating point numbers:

import numpy as np

lengths = [3, 2, 4] # Deduced values of lengths from your output.
percent = []

for i in range(3): # Deduced size of F300 from the length of percent.

    percent.append(np.zeros(lengths[i]))

for i in range(0, len(percent)):

    for j in range(0, lengths[i]): #

        percent[i][j] = float(j + 1) / float(lengths[i])

Another approach would be to import division from the __future__ package. However, this import line must be the first statement in your code.

from __future__ import division
import numpy as np

lengths = [3, 2, 4] # Deduced values of lengths from your output.
percent = []

for i in range(3): # Deduced size of F300 from the length of percent.

    percent.append(np.zeros(lengths[i]))

for i in range(0, len(percent)):

    for j in range(0, lengths[i]):

        percent[i][j] = (j + 1) / lengths[i]

The third approach, and the one I personally prefer, is to make good use of NumPy's built-in functions:

import numpy as np

lengths = [3, 2, 4] # Deduced values of lengths from your output.
percent = np.array([np.linspace(1.0 / float(l), 1.0, l) for l in lengths])

All three approaches will produce a list (or in the last case, numpy.ndarray object) of numpy.ndarray objects with the following values:

[[0.33333333, 0.66666667, 1.], [0.5, 1.], [0.25, 0.5, 0.75, 1.]]

Upvotes: 1

Related Questions