1

I'm printing

print(f"my named tuple: {my_tuple}")

a namedtuple that contains integers, floats, strings and lists of each of these:

MyTuple = namedtuple(
    "MyTuple",
    ["my_int", "my_float", "my_str", "my_float_list"],
)
my_tuple = MyTuple(42, 0.712309841231, "hello world", [1.234871231231,5.98712309812,3.623412312e-2])

The output is something like

MyTuple = (my_int=42, my_float=0.712309841231, my_str="hello world", my_float_list=[1.234871231231,5.98712309812,3.623412312e-2])

Is there any way I can automatically round the floats both in- and outside lists to, say, 2 decimal digits so that these tuples don't clog up my logs as much?

Janosh
  • 3,392
  • 2
  • 27
  • 35

1 Answers1

1

You could do in this way:

my_tuple = (42, 0.712309841231, "hello world", [1.234871231231,5.98712309812,3.623412312e-2, 'cc', 12])
l = []
for i in my_tuple:
    if isinstance(i, float):
        i = format(i, ".2f")
        l.append(float(i))
    elif isinstance(i, list):
        i = [float(format(el, ".2f")) if isinstance(el, float) else el for el in i]
        l.append(i)
    else:
        l.append(i)

from collections import namedtuple
MyTuple = namedtuple("MyTuple",["my_int", "my_float", "my_str", "my_float_list"],)
my_tuple = MyTuple(*l)
print (my_tuple)

Output:

MyTuple(my_int=42, my_float=0.71, my_str='hello world', my_float_list=[1.23, 5.99, 0.04, 'cc', 12])
Joe
  • 12,057
  • 5
  • 39
  • 55
  • Note that the lists don't all contain floats as mentioned in my question. Some contain integers or strings. – Janosh Nov 23 '18 at 13:42
  • @Casimir I've updated the answer. Please check if it is ok – Joe Nov 23 '18 at 13:58
  • Is there a way to retain the keywords (`my_int=..., my_float=...`) in the printed output? I tried to redefine the `__str__` method as suggested in the [linked duplicate](https://stackoverflow.com/questions/7914152/can-i-overwrite-the-string-form-of-a-namedtuple) and then in the end feed it back into the constructor, i.e. `def __str__(self): {... your code ...} return str(MyTuple(*l))` but that runs into a max recursion error. – Janosh Nov 23 '18 at 16:57
  • You Can try with`my_tuple = MyTuple(*l)` after the `for loop` – Joe Nov 23 '18 at 17:30
  • Yes, that's what I tried. – Janosh Nov 24 '18 at 12:04
  • @Casimir I've updated the complete code, please check it :) – Joe Nov 26 '18 at 06:37