简体   繁体   English

在混合类型的嵌套元组中打印格式化的浮点数

[英]Printing formatted floats in nested tuple of mixed type

I have a list of tuples where the entries in the tuples are mixed type (int, float, tuple) and want to print each element of the list on one line.我有一个元组列表,其中元组中的条目是混合类型(int、float、tuple),并且想要在一行上打印列表的每个元素。

Example list:示例列表:

 [('520',
     (0.26699505214910974, 9.530913611077067e-22, 1431,
     (0.21819421133984918, 0.31446394340528838), 11981481)),
 ('1219',
     (0.2775519783082116, 2.0226340976042765e-25, 1431,
     (0.22902629625165472, 0.32470159534237308), 14905481))]

I would like to print each tuple as a single line with the floats formatted to print to the ten-thousandth place:我想将每个元组打印为一行,并将浮点数格式化为打印到第 10000 个位置:

 [('520', (0.2669, 9.5309e-22, 1431, (0.2181, 0.3144), 11981481)),
 ('1219', (0.2775, 2.0226e-25, 1431, (0.2290, 0.3247), 14905481))]

I was using pprint to get everything on one line我正在使用pprint将所有内容都放在一行上

pprint(myList, depth=3, compact=True)
> ('1219', (0.2775519783082116, 2.0226340976042765e-25, 1431, (...), 14905481))]

but I wasn't sure how to properly format the floats in a pythonic manner.但我不确定如何以 Pythonic 的方式正确格式化浮点数。 (There has to be a nicer way of doing it than looping through the list, looping through each tuple, checking if-float/if-int/if-tuple and converting all floats via "%6.4f" % x ). (必须有比循环遍历列表更好的方法,循环遍历每个元组,检查 if-float/if-int/if-tuple 并通过"%6.4f" % x转换所有浮点数)。

This is not exactly what you need, but very close, and the code is pretty compact.这不是您真正需要的,但非常接近,并且代码非常紧凑。

def truncateFloat(data):
    return tuple( ["{0:.4}".format(x) if isinstance(x,float) else (x if not isinstance(x,tuple) else truncateFloat(x)) for x in data])
pprint(truncateFloat(the_list))

For your example the result is对于您的示例,结果是

(('520', ('0.267', '9.531e-22', 1431, ('0.2182', '0.3145'), 11981481)),
 ('1219', ('0.2776', '2.023e-25', 1431, ('0.229', '0.3247'), 14905481)))

You can play with options of .format() to get what you want.你可以使用.format()选项来获得你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM