How to round certain values in list

Question:

I have a list in Python

a = [100.50, 121.50, 130.50, 140.50, 150.50, 160.50, 170.50, 180.50, 190.50, 200.50] 

I want to round first three values

 [100.00, 100.00, 100.00, 140.50, 150.50, 160.50, 170.50, 180.50, 190.50, 200.50]

I need to round down to 100.0 if they are < 130.0 and then similarly round down to 200 if they are < 230 and so on.

Asked By: Ave

||

Answers:

Slice the list, apply round(), re-assign the list:

>>> a[:3] = map(round, a[:3])
>>> a
[100, 122, 130, 140.5, 150.5, 160.5, 170.5, 180.5, 190.5, 200.5]

Note, I’m assuming you want to round the values and not make them all 100. Otherwise, you can use a function like this:

>>> from math import log10, floor
>>> def round_to_1(x):
...     return round(x, -int(floor(log10(abs(x)))))
... 
>>> a[:3] = list(map(round_to_1, a[:3]))
>>> a
[100.0, 100.0, 100.0, 140.5, 150.5, 160.5, 170.5, 180.5, 190.5, 200.5]
Answered By: Chris_Rands
>>> def round_first_n(arr, n):
...     for i in range(n):
...             arr[i] = round(arr[i])
...
>>> arr = [100.5]*10
>>> arr
[100.5, 100.5, 100.5, 100.5, 100.5, 100.5, 100.5, 100.5, 100.5, 100.5]
>>> round_first_n(arr, 3)
>>> arr
[100, 100, 100, 100.5, 100.5, 100.5, 100.5, 100.5, 100.5, 100.5]

To round at arbitrary indices:

>>> def round_at(arr, indices):
...     for i in indices:
...             arr[i] = round(arr[i])
...
>>> round_at(arr, [5,7])
>>> arr
[100, 100, 100, 100.5, 100.5, 100, 100.5, 100, 100.5, 100.5]
Answered By: lmeninato

Based on comments it seems you want to round down to 100.0 if they are < 130.0 and then similarly round down to 200 if they are < 230 and so on.

So the following:

b = [100*(x//100) if x % 100 < 30 else x for x in a]

So for every element x of list a, if the remainder of dividing it by 100 is less than 30 we have to round it down other wise keep x.

For rounding down to 100, 200, … integer divide x by 100 and then multiply again by 100.

Example

a = [100.50, 121.50, 130.50, 220.50, 240.50, 310.50, 350.50]

Output

    [100.0, 100.0,   130.5,  200.0,  240.5,  300.0,  350.5]
Answered By: re-za
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.