我有一个数字[0,10,20,30,40,50]的列表,现在此列表将由诸如33,43的随机数附加,我每次在列表中未附加任何编号时都要检查该列表,并且我希望将它们四舍五入为30和40。
Use the round()
built-in function. In conjuction with a list comprehension , can give us an expressive one-line function!
def round_list(l):
return [int(round(i, -1)) for i in l]
Sample output:
l = [24, 34, 41, 40, 12, 434, 53, 53]
print round_list(l)
>>> [20, 30, 40, 40, 10, 430, 50, 50]
In order to round to the nearest 10 you can:
The code below should contain what you need:
import random
l = [0.0, 10.0, 20.0, 30.0, 40.0, 50.0]
# generate a random number
random_number = random.uniform(30, 100)
# round the number to nearest 10
def round_number(num):
x = round(num/10) * 10
return x
rounded_number = round_number(random_number)
# append to the list
l.append(rounded_number)
Testing the above:
>>> print random_number
64.566245501
>>> print rounded_number
60.0
>>> print l
[0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.