我有
d = {'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592}
我想将它打印到 std 但我想格式化数字,比如删除过多的小数位,比如
{'a':'Ali', 'b':2341, 'c':0.24, 'p':3.14}
显然我可以遍历所有项目并查看它们是否是我想要格式化和格式化并打印结果的“类型”,
但是,当__str__()
ing 或以某种方式输出要打印的字符串时,是否有更好的方法来格式化
字典中的所有数字?
编辑:
我正在寻找像这样的魔法:
'{format only floats and ignore the rest}'.format(d)
或来自 yaml
世界或类似的东西。
最佳答案
您可以使用 round
将 float 四舍五入到给定的精度。要识别 float ,请使用 isinstance
:
>>> {k:round(v,2) if isinstance(v,float) else v for k,v in d.iteritems()}
{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}
round
帮助:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
更新:
您可以创建 dict
的子类并覆盖 __str__
的行为:
class my_dict(dict):
def __str__(self):
return str({k:round(v,2) if isinstance(v,float) else v
for k,v in self.iteritems()})
...
>>> d = my_dict({'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592})
>>> print d
{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}
>>> "{}".format(d)
"{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}"
>>> d
{'a': 'Ali', 'p': 3.141592, 'c': 0.2424242421, 'b': 2341}
关于python - 在 python 中打印具有格式的混合类型字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489353/