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

Sal*_*Sal 6 python pretty-print pprint

我有一个元组列表,其中元组中的条目是混合类型(int、float、tuple),并且想要在一行上打印列表的每个元素。

示例列表:

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

我想将每个元组打印为一行,并将浮点数格式化为打印到万分之一:

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

我过去常常pprint把所有事情都放在一条线上

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

但我不确定如何以Python方式正确格式化浮点数。(必须有一种比循环列表、循环每个元组、检查 if-float/if-int/if-tuple 并通过 转换所有浮点数更好的方法"%6.4f" % x)。

小智 3

这并不完全是您所需要的,但非常接近,并且代码非常紧凑。

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))
Run Code Online (Sandbox Code Playgroud)

对于你的例子,结果是

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

您可以选择 来.format()获得您想要的东西。