Rounding floats in Python

Viewed 130

I have a large list of floats between 0 and 1 as seen below:

l1 = [0,0.2,0.9,0.75,0.3,1,0.43,0.65]

what i would like is to round these floats to the numbers:

l2 = [0,0.25,0.5,0.75,1]

Result here would be:

r = [0,0.25,1,0.75,0.5,1,0.5,0.75]

What i mean is for every item in l1 choose the item that is closer to it from l2 and replace with the latter. I could implement this using some for loops and check exhaustively but i was hoping for a slicker solution.

Is there a library in Python to achieve this elegantly?

2 Answers

If l2 is always [0, 0.25, 0.5, 0.75, 1] you can use numpy:

r = np.round(4*np.array(l1))/4

Output:

array([0.  , 0.25, 1.  , 0.75, 0.25, 1.  , 0.5 , 0.75])

If you want to only round up, use numpy.ceil:

r = np.ceil(4*np.array(l1))/4

Output:

array([0.  , 0.25, 1.  , 0.75, 0.5 , 1.  , 0.5 , 0.75])

Here's one way using round:

l1 = [round(n*4)/4 for n in l1]
print(l1)

Ouput:

[0.0, 0.25, 1.0, 0.75, 0.25, 1.0, 0.5, 0.75]
Related