更改默认的浮动打印格式 [英] Change default float print format

查看:165
本文介绍了更改默认的浮动打印格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些列表和更复杂的结构包含浮游物。打印时,我看到有很多十进制数字的浮点数,但打印时,我不需要所有的浮点数。
所以我想定义一个自定义格式(例如2或3小数),当浮动打印。

我需要使用浮动而不是十进制。还有,我不允许截断/四舍五入浮点数。

有没有办法改变默认的行为?



我建议你找到一个更好的解决方案,如只打印浮动< $ m $ c>%0.2f printf表示法:

  b $ b print'%0.2f'%item,



  print.join(mylist中item的'%0.2f'%item)


I've some lists and more complex structures containing floats. When printing them, I see the floats with a lot of decimal digits, but when printing, I don't need all of them. So I would like to define a custom format (e.g. 2 or 3 decimals) when floats are printed.

I need to use floats and not Decimal. Also, I'm not allowed to truncate/round floats.

Is there a way to change the default behavior?

解决方案

You are not allowed to monkeypatch C types, like Ignacio said.

However, if you are terribly pressed in doing so and you know some C, you could go modify the Python interpreter source code yourself, then recompile it into a custom solution. Once I modified one of the standard behaviors for lists and it was only a moderate pain.

I suggest you find a better solution, such as just printing the floats with the "%0.2f" printf notation:

for item in mylist:
    print '%0.2f' % item,

or

print " ".join('%0.2f' % item for item in mylist)

这篇关于更改默认的浮动打印格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆