rounding-up numbers within a tuple

后端 未结 3 1266
囚心锁ツ
囚心锁ツ 2021-01-19 01:53

Is there anyway I could round-up numbers within a tuple to two decimal points, from this:

(\'string 1\', 1234.55555, 5.66666, \'string2\')

3条回答
  •  感情败类
    2021-01-19 02:19

    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')
    

提交回复
热议问题