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:
JavaScript
x
4
1
returnList = [('mountain_113', (1.5, 1.0, 1.0338541666666667, 1.9166666666666667, 0.6614583333333334, 1.2598673502604167, 0.03375385780420761, 2.3029198140922946, 0.1698906919822926, 0.746665039060726)),
2
('street_gre295', (2.0, 1.033203125, 0.84375, 0.7421875, 0.9375, 0.654083251953125, 1.9498253377306005, 1.7506276776130898, 1.1736444973883702, 0.6882098607982887)),
3
('opencountry_134', (1.0, 0.99609375, 1.10546875, 1.875, 0.9296875, 1.740234375, 0.015625, 1.90625, 0.0625, 0.75))]
4
I have the following code
JavaScript
1
3
1
def format(inter): return f'{inter:.1f}'
2
[print(' '.join( list(map(format, n[1])) )) if i!=0 else print(n[0]) for i,n in enumerate(returnList)]
3
However it is causing a error such as
JavaScript
1
7
1
Traceback (most recent call last):
2
File "main.py", line 69, in <module>
3
[print(' '.join( list(map(format, n[1])) )) if i!=0 else print(n[0]) for i,n in enumerate(listStatics)]
4
File "main.py", line 69, in <listcomp>
5
[print(' '.join( list(map(format, n[1])) )) if i!=0 else print(n[0]) for i,n in enumerate(listStatics)]
6
TypeError: 'float' object is not iterable
7
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
JavaScript
1
4
1
mountain_113 1.5 1.0 1.0 1.9 0.7 1.3 0.0 2.3 0.2 0.7
2
street_gre295 2.0 1.0 0.8 0.7 0.9 0.7 1.9 1.8 1.2 0.7
3
opencountry_134 1.0 1.0 1.1 1.9 0.9 1.7 0.0 1.9 0.1 0.8
4
Advertisement
Answer
JavaScript
1
3
1
for i, t in returnList:
2
print(i, " ".join(map("{:.1f}".format, t)))
3
Prints:
JavaScript
1
4
1
mountain_113 1.5 1.0 1.0 1.9 0.7 1.3 0.0 2.3 0.2 0.7
2
street_gre295 2.0 1.0 0.8 0.7 0.9 0.7 1.9 1.8 1.2 0.7
3
opencountry_134 1.0 1.0 1.1 1.9 0.9 1.7 0.0 1.9 0.1 0.8
4
If you want to call your format function:
JavaScript
1
6
1
def format(inter):
2
return f"{inter:.1f}"
3
4
for i, t in returnList:
5
print(i, " ".join(map(format, t)))
6