0

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?

3
  • You print one value after the other. You have multiple options - if it's just about how it's displayed, you could tell print to not print newlines and add a space. Otherwise, you'd probably want to save the values of b in a list and in the end print that - or do the whole loop as a list comprehension instead. Do you want to continue processing it later, or do you just care about printing? And will the loop remain this simple? Commented Apr 16, 2021 at 6:46
  • try like this print(a, end=" ") or print(b, end=" ") Commented Apr 16, 2021 at 6:46
  • Thank you. I want to continue processing it later. I put the print just to see how it looks. Commented Apr 16, 2021 at 6:55

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Or as a list comprehension: [4*n*(n<=4) for n in j]
Multiplying by the boolean, that's a neat trick, first time I've seen it :-)
tobias_k, must admit your solution is very unique!
Of course you can also use a more conventional list comprehension with a ternary expression like [4*n if n <= 4 else 0.0 for n in j] instead of that "multiply by boolean" trick.

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.