rounding-up numbers within a tuple
Is there anyway I could round-up numbers within a tuple to two decimal points, from this:
('string 1', 1234.55555, 5.66666, 's开发者_JS百科tring2')
to this:
('string 1', 1234.56, 5.67, 'string2')
Many thanks in advance.
If your tuple has a fixed size of 4 and the position of the floats is always the same, you can do this:
>>> t = ('string 1', 1234.55555, 5.66666, 'string2')
>>> t2 = (t[0], round(t[1], 2), round(t[2], 2), t[3])
>>> t2
('string 1', 1234.56, 5.67, 'string2')
The general solution would be:
>>> t2 = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, t))
>>> t2
('string 1', 1234.56, 5.67, 'string2')
List comprehension solution:
t = ('string 1', 1234.55555, 5.66666, 'string2')
solution = tuple([round(x,2) if isinstance(x, float) else x for x in t])
To avoid issues with floating-point rounding errors, you can use decimal.Decimal
objects:
"""
>>> rounded_tuple(('string 1', 1234.55555, 5.66666, 'string2'))
('string 1', Decimal('1234.56'), Decimal('5.67'), 'string2')
"""
from decimal import Decimal
def round_if_float(value):
if isinstance(value, float):
return Decimal(str(value)).quantize(Decimal('1.00'))
else:
return value
def rounded_tuple(tup):
return tuple(round_if_float(value) for value in tup)
rounded_tuple
uses a generator expression inside a call to tuple.
精彩评论