通过列表理解使用 f 字符串以格式化形式打印元组列表

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

我想以格式化的形式打印出元组列表... 我有以下列表,其中包含一个由字符串和其他浮点数组成的元组:

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

我有以下代码

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

但是它会导致错误,例如

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

我需要按如下方式打印它们:打印元组的第一个元素,然后对于第二个元素的每个浮点数,使用 format 函数

我希望使用列表理解来打印它...对于 dalta 示例,它应该在下方输出数据

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
for i, t in returnList:
    print(i, " ".join(map("{:.1f}".format, t)))

打印:

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

如果你想调用你的格式函数:

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

这应该有效:

for t in returnList:
    datapoints = [str(dt) for dt in t[1]]
    print('{} {}'.format(t[0], " ".join(datapoints)))