[Tutor] formatting and pretty printing nested structures

Terry Carroll carroll at tjc.com
Mon Feb 23 14:38:36 EST 2004


On Mon, 23 Feb 2004, kevin parks wrote:

> Hi. I have a list of lists. Inside the list are lists that are made up 
> of strings and floats. When i print the list it prints the floats in 
> the usual insane long wierdo format and i want to print them with 
> string formatting so that they are more readable, so i somehow have to 
> pick apart the nested items so that i can print:
> 
> 0 ['C', 8.0, 8.0]
> 1 ['C#', 8.0099999999999998, 8.0833349227905273]
> 
> more like this:
> 
> 0 ['C', 8.00, 8.000000]
> 1 ['C#', 8.01, 8.083333]
> 
> or even betterererer:
> 
> 0    C    8.00    8.000000
> 1    C#   8.01    8.083333

Here's one approache; lining up the numbers is lefta s an exercise to the 
reader.  :-)

def printthelist(thelist, intformat="%d", floatformat="%.2f"):
    for entry in thelist:
        if isinstance(entry,list):
            printthelist(entry, intformat=intformat, floatformat=floatformat)
        else:
            try:
                entry+1
                if repr(entry).isdigit():
                    print intformat % entry,
                else:
                    print floatformat % entry,
            except TypeError:
                print entry,

list0 = [0, ['C', 8.0, 8.0]]
list1 = [1, ['C#', 8.0099999999999998, 8.0833349227905273]]

printthelist(list0)
print
printthelist(list1)
print


gives:

0 C 8.00 8.00
1 C# 8.01 8.08




More information about the Tutor mailing list