Home > Back-end >  Format problem in a construction of a loop in python
Format problem in a construction of a loop in python

Time:09-21

Following is the piece of program:

import numpy as np
def f(num):
  return np.piecewise(num, [(num 1)%3==1, (num 2)%3==0,(num 1)%3==0], [1,-1,-1])
print(f(0))
print(f(1))
fx = [[f(i),i,(i 1)%2] for i in range(2)] 
print(fx)

Output:

  1
 -1
  [[array(1), 0, 1], [array(-1), 1, 0]]

I am expecting following output for the construction: fx = [[f(i),i,(i 1)%2] for i in range(2)]

 [[1.0, 0, 1], [-1.0, 1, 0]]

Kindly help.

CodePudding user response:

Try using the item function:

fx = [[f(i).item(), i, (i   1) % 2] for i in range(2)] 

CodePudding user response:

This happens because you're returning a numpy array, which is returned as array([data]). If you use the item() function you can fetch it's value.

fx = [[f(i).item(), i, (i   1) % 2] for i in range(2)]

If you have multiple values in the array, then use you can use item(n).

  • Related