ede*_*esz 8 python list rounding python-2.7
我有一个只有浮点数的Python列表:
list_num = [0.41, 0.093, 0.002, 1.59, 0.0079, 0.080, 0.375]
Run Code Online (Sandbox Code Playgroud)
我需要将此列表四舍五入以获得:
list_num_rounded = [0.4, 0.09, 0.002, 1.5, 0.007, 0.08, 0.3]
Run Code Online (Sandbox Code Playgroud)
问题: 1.59到1.5的舍入很容易.但是,我的问题是浮点数小于1.
问题: 基本上,我需要向下舍入所有浮点数,以便:如果浮点数<1,则舍入版本只包含一个非零数字.有没有办法在Python 2.7中执行此操作?
编辑:
尝试: 这是我尝试过的:
list_num_rounded = []
for elem in list_num:
if elem > 0.01 and elem < 0.1:
list_num_rounded.append(round(elem,2))
if elem > 0.001 and elem < 0.01:
list_num_rounded.append(round(elem,3))
elif elem > 0.1:
list_num_rounded.append(round(elem,1))
Run Code Online (Sandbox Code Playgroud)
但是,这给出了:
[0.4, 0.09, 0.002, 1.6, 0.008, 0.08, 0.4]
Run Code Online (Sandbox Code Playgroud)
它向上舍入1.59,0.79和0.375,但我需要一种方法来向下舍入.有没有办法做到这一点?
编辑2:
该列表不包含负浮点数.只有正浮标才会出现.
您可以使用对数计算出有多少个前导零,然后就需要一种四舍五入的方法。一种方法是像这样使用地板:
import math
list_num = [0.41, 0.093, 0.002, 1.59, 0.0079, 0.080, 0.375, 0, 10.1, -0.061]
def myround(n):
if n == 0:
return 0
sgn = -1 if n < 0 else 1
scale = int(-math.floor(math.log10(abs(n))))
if scale <= 0:
scale = 1
factor = 10**scale
return sgn*math.floor(abs(n)*factor)/factor
print [myround(x) for x in list_num]
Run Code Online (Sandbox Code Playgroud)
输出:
[0.4, 0.09, 0.002, 1.5, 0.007, 0.08, 0.3]
Run Code Online (Sandbox Code Playgroud)
我不确定如何处理负数和大于1的数,这会将负数向上舍入并将大于1的数变为1dp。