Abhishek dot py Abhishek dot py - 18 days ago 10
Python Question

Round off some values of a tuple

I have tuples like this ( I not sure will it call a list of tuple or not ! )

ratings = [('5', 45.58139534883721), ('4', 27.44186046511628), ('3', 20.0), ('2', 5.116279069767442), ('1', 1.8604651162790697)]


I want to make second value round off ( or truncate, don't matter to me )up to 2 decimal place, like this:

[('5', 45.58), ('4', 27.44), ('3', 20.0), ('2', 5.11), ('1', 1.86)]


I tried something like this:

l = tuple([round(x,2) if isinstance(x, float) else x for x in ratings])


But this seems to be not working. What can I try?

Answer

Round the 2nd element of your tuples only:

ratings = [('5', 45.58139534883721), ('4', 27.44186046511628), ('3', 20.0), ('2', 5.116279069767442), ('1', 1.8604651162790697)]
l = [(item[0],round(item[1],2)) for item in ratings]
# [('5', 45.58), ('4', 27.44), ('3', 20.0), ('2', 5.12), ('1', 1.86)]