2

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
kokorilos
  • 21
  • 1
  • 1
    Can the values in `l2` change or do you just want to round each number to the closest quarter? – Iain Shelvington Apr 18 '22 at 19:30
  • Judging by the answers here: https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value there doesn't seem to be a library that will do this – Nin17 Apr 18 '22 at 19:30
  • 1
    "for every item in l1 choose the item that is closer to it from l2 and replace with the latter" - are you strictly rounding up? Because `0.3` is closer to `0.25`, yet your expected output has `0.5`. – shriakhilc Apr 18 '22 at 19:33
  • Depending on your real needs, this is a duplicate of either [From list of integers, get number closest to a given value](https://stackoverflow.com/q/12141150/364696) (the distinction is immaterial for `int` vs. `float`) or [Python - Rounding by quarter-intervals](https://stackoverflow.com/q/8118679/364696), so I've duped to those. – ShadowRanger Apr 18 '22 at 19:36
  • If you actually do want to round up, you can use NumPy: `np.digitize(l1, l2, right=True)`. But it's not clear if that's what you want, so I voted to close the question as "unclear" until you can clarify it. BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Apr 18 '22 at 19:38

2 Answers2

2

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])
Nin17
  • 2,821
  • 2
  • 4
  • 14
1

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]
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
  • According to OP, `0.3` should round to `0.5`, not `0.25`. It's not clear if that's a mistake or if they specifically want to round up. – wjandrea Apr 18 '22 at 19:35