hm1
hm1

Reputation: 5

Converting python loop output into an array

I am trying to convert a python from loop output into an array. For example in the following code, I wanted the output as b = [6.0, 14.0, 0.0, 0.0, 0.0] but it gives the output as a column.

import numpy as np
j  = np.arange(1.5, 10.0, 2)
for m in j: 
    a = 2*m    
    if a <= 8:
        b = 2*a
        print(b)        
    else:
         b = 0.0
         print(b) 

I have tried to define the output b as numpy.array but it does not work. Any idea?

Upvotes: 0

Views: 157

Answers (1)

joao
joao

Reputation: 2293

It's good practice to separate the creation of a data structure from whatever use you make of it, such as printing it, so you could create the b first, then print it:

import numpy as np
j  = np.arange(1.5, 10.0, 2)
b = []
for m in j: 
    a = 2*m    
    if a <= 8:
        b.append(2*a)
    else:
         b.append(0.0)
print(b)

As it happens, python's default is to print the array horizontally:

[6.0, 14.0, 0.0, 0.0, 0.0]

Upvotes: 1

Related Questions