我的L1数组包含像0.029999999999999999这样的数字,我想打印为0.03
我的代码有效,但最后会出错,因为最后一次计数超出了范围.我明白为什么它会破裂,但不知道如何解决它.谢谢
count = 1
while L1:
print "%.2f" %L1[count]
count = count + 1
Run Code Online (Sandbox Code Playgroud)
如果要打印所有数字L1,请使用:
for x in L1: print '%.2f' % x
Run Code Online (Sandbox Code Playgroud)
如果你想跳过第一个,那就行了for x in L1[1:]:.
编辑:OP在评论(!)中提到他们的愿望实际上是"创建一个新阵列"(我想他们实际上意味着"一个新的列表",而不是一个array.array,但这不会是非常不同).在浮动世界中没有"圆形数字" - 你可以使用round(x, 2),但这仍然会给你一个浮动,所以它不一定有"正好2位数".无论如何,对于字符串列表:
newlistofstrings = ['%.2f' % x for x in L1]
Run Code Online (Sandbox Code Playgroud)
或者对于带有十进制数字的数字(如果需要,可以正好有2位数字):
import decimal
newlistofnnumbers = [decimal.Decimal('%.2f') % x for x in L1]
Run Code Online (Sandbox Code Playgroud)