[英]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我需要按如下方式打印它们:打印元组的第一个元素,然后将第二个元素的每个浮点数打印出来,格式为 function
I would like it to be printed using the list comprehension... For the dalta sample it should output the data down bellow我希望它使用列表理解打印...对于 dalta 示例,它应该 output 数据如下
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)))
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:如果你想调用你的格式 function:
def format(inter):
return f"{inter:.1f}"
for i, t in returnList:
print(i, " ".join(map(format, t)))
This should work:这应该有效:
for t in returnList:
datapoints = [str(dt) for dt in t[1]]
print('{} {}'.format(t[0], " ".join(datapoints)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.