如何舍入向量数组的值

时间:2018-04-18 05:21:33

标签: python arrays vector rounding

我正在研究Python代码,我需要对以下数组的值进行舍入:

P = [[3.2, 3.7, 2.1],
    [4.5, 2.1, 2.3],
    [3.1, 2.5]]

最后得到:

 P= [[3, 4, 2],
     [5, 2, 2],
     [3, 3]]

我尝试了以下方法,但它不起作用。

  for i in range(len(P)):
    P[i] = int(round(P[i], 0))

1 个答案:

答案 0 :(得分:1)

您可以使用列表推导:

P= [[3.2, 3.7, 2.1],
    [4.5, 2.1, 2.3],
    [3.1, 2.5]]

P2 = [[int(round(x,0)) for x in y] for y in P]
# P is your list of lists
# y is each inner list
# x is each element in y
# rounding logic is as yours

print(P2)

输出:

 [[3, 4, 2], [5, 2, 2], [3, 3]]

编辑:2.7和3.6表现不同 - 我使用了2.7 shell。

请参阅round()

  

注意浮点数round()的行为可能会令人惊讶:for   例如,round(2.675,2)给出2.67而不是预期的2.68。这个   这不是一个错误:它是大多数小数部分的结果   不能完全表示为浮点数。有关详细信息,请参阅Floating Point Arithmetic: Issues and Limitations

您可以通过创建自己的圆形方法来修复它:

def myRounder(num):
    return int(num)+1 if num - int(num) >= 0.5 else int(num)    

P= [[3.2, 3.7, 2.1],
    [4.5, 2.1, 2.3],
    [3.1, 2.5]]

P2 = [[int(myRounder(x)) for x in y] for y in P]
# P is your list of lists
# y is each inner list
# x is each element in y
# rounding logic is as yours

print(P2)

这将在2.7和3.x上产生相同的结果。