Reputation: 49
I'm working on a Python code and I need to round the values of this following array:
P = [[3.2, 3.7, 2.1],
[4.5, 2.1, 2.3],
[3.1, 2.5]]
And finally get:
P= [[3, 4, 2],
[5, 2, 2],
[3, 3]]
I tried the following method but it doesn't work.
for i in range(len(P)):
P[i] = int(round(P[i], 0))
Upvotes: 2
Views: 1004
Reputation: 51643
You can use list comprehensions:
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)
Output:
[[3, 4, 2], [5, 2, 2], [3, 3]]
Edit: 2.7 and 3.6 behave differently - I used a 2.7 shell.
See round()
Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
You can fix it by creating your own round-Method:
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)
This will lead to the same results on 2.7 and 3.x.
Upvotes: 2