内有反正我可以一个元组内围捕号码两个小数点, 从这个:凑整数字的元组
('string 1', 1234.55555, 5.66666, 'string2')
这样:
('string 1', 1234.56, 5.67, 'string2')
非常感谢提前。
内有反正我可以一个元组内围捕号码两个小数点, 从这个:凑整数字的元组
('string 1', 1234.55555, 5.66666, 'string2')
这样:
('string 1', 1234.56, 5.67, 'string2')
非常感谢提前。
如果你的元组有4固定的大小和彩车的位置总是一样的,你可以这样做:
>>> 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')
一般的解决办法是:
>>> t2 = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, t))
>>> t2
('string 1', 1234.56, 5.67, 'string2')
名单理解的解决方案:
t = ('string 1', 1234.55555, 5.66666, 'string2')
solution = tuple([round(x,2) if isinstance(x, float) else x for x in t])
为了避免issues with floating-point rounding errors,您可以使用decimal.Decimal
个对象:
"""
>>> 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
使用generator expression调用元组内。
SO上有相关线程:http://stackoverflow.com/questions/455612/python-limiting-floats-to-two-decimal-points – pyfunc 2010-10-13 22:33:57