我有一个Python列表,只有浮点数:
list_num = [0.41, 0.093, 0.002, 1.59, 0.0079, 0.080, 0.375]
我需要将这个列表四舍五入得到:
list_num_rounded = [0.4, 0.09, 0.002, 1.5, 0.007, 0.08, 0.3]
问题: 将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))
然而,这样会得到:
[0.4, 0.09, 0.002, 1.6, 0.008, 0.08, 0.4]
它将1.59、0.79和0.375四舍五入,但我需要一种只舍不入的方法。有什么办法吗?
列表中不包含负浮点数,只有正浮点数。
if
语句来单独处理这种情况。我将接受这个答案,因为您的函数似乎对原帖中列出的所有其他情况都有效。谢谢! - edesz