Skip to content
Advertisement

Printing a list of tuples in a formated form with f-strings by a list comprehension

I want to print out a list of tuples in a formated form… I have the following list which contains a tuple formed by a string and other tuple of floats:

   returnList = [('mountain_113', (1.5, 1.0, 1.0338541666666667, 1.9166666666666667, 0.6614583333333334, 1.2598673502604167, 0.03375385780420761, 2.3029198140922946, 0.1698906919822926, 0.746665039060726)), 
                  ('street_gre295', (2.0, 1.033203125, 0.84375, 0.7421875, 0.9375, 0.654083251953125, 1.9498253377306005, 1.7506276776130898, 1.1736444973883702, 0.6882098607982887)),
                  ('opencountry_134', (1.0, 0.99609375, 1.10546875, 1.875, 0.9296875, 1.740234375, 0.015625, 1.90625, 0.0625, 0.75))]

I have the following code

def format(inter):  return f'{inter:.1f}'
[print(' '.join( list(map(format, n[1])) )) if i!=0 else print(n[0]) for i,n in enumerate(returnList)]

However it is causing a error such as

Traceback (most recent call last):
  File "main.py", line 69, in <module>
    [print(' '.join( list(map(format, n[1])) )) if i!=0 else print(n[0]) for i,n in enumerate(listStatics)]
  File "main.py", line 69, in <listcomp>
    [print(' '.join( list(map(format, n[1])) )) if i!=0 else print(n[0]) for i,n in enumerate(listStatics)]
TypeError: 'float' object is not iterable

I need to print them as follows: print the first element of the tuple, then for each float of the second element print them out whith the format function

I would like it to be printed using the list comprehension… For the dalta sample it should output the data down bellow

mountain_113 1.5 1.0 1.0 1.9 0.7 1.3 0.0 2.3 0.2 0.7
street_gre295 2.0 1.0 0.8 0.7 0.9 0.7 1.9 1.8 1.2 0.7
opencountry_134 1.0 1.0 1.1 1.9 0.9 1.7 0.0 1.9 0.1 0.8

Advertisement

Answer

for i, t in returnList:
    print(i, " ".join(map("{:.1f}".format, t)))

Prints:

mountain_113 1.5 1.0 1.0 1.9 0.7 1.3 0.0 2.3 0.2 0.7
street_gre295 2.0 1.0 0.8 0.7 0.9 0.7 1.9 1.8 1.2 0.7
opencountry_134 1.0 1.0 1.1 1.9 0.9 1.7 0.0 1.9 0.1 0.8

If you want to call your format function:

def format(inter):
    return f"{inter:.1f}"
    
for i, t in returnList:
    print(i, " ".join(map(format, t)))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement