I'm having some issue to round up and down of a list of number to the nearest 1000.
Below is my code:
rev_list = []
for i in range(12):
rev = int(round(random.normalvariate(100000, 12000)))
rev_list.append(rev)
print(rev_list)
The output is:
[97277, 96494, 104541, 132060, 98179, 87862, 84718, 95391, 94674, 89773, 92790, 86122]
I would like to round the list to the nearest 1000. How can I do that?
4,725 to the nearest 1,000 is 5,025 Page 9 A number is shown in the place value chart.
We will change the digit in hundreds places to 0 and add 1 to the digit in thousands places. So, the nearest thousand to 3500 is 4000.
The round
function can take negative digits to round to, which causes it to round off to the left of the decimal. For example:
>>> round(15768, -3)
16000
>>> round(1218, -3)
1000
So the short answer is: Call round
with the second argument of -3
to round to the nearest 1000.
List comprehension is a one-line loop which allows you to apply a function to the list items. (for more read List Comprehensions)
[x for x in rev_list]
In this case, round(num, -3) is the function.
>>> round(1300,-3)
1000
>>>
The answer
You can apply a function on a list by this code
rev_list=[round(x,-3) for x in rev_list]
The example:
>>> rev_list=[97277, 96494, 104541, 132060, 98179, 87862, 84718, 95391, 94674, 89773, 92790, 86122]
>>> rev_list=[round(x,-3) for x in rev_list]
>>> rev_list
[97000, 96000, 105000, 132000, 98000, 88000, 85000, 95000, 95000, 90000, 93000, 86000]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With