【问题标题】:Printing a mixed type dictionary with format in python在python中打印带有格式的混合类型字典
【发布时间】:2013-07-03 14:01:48
【问题描述】:

我有

d = {'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592}

我想将它打印到 std 但我想格式化数字,比如删除过多的小数位,比如

{'a':'Ali', 'b':2341, 'c':0.24, 'p':3.14}

显然我可以浏览所有项目,看看它们是否是“类型”,我想对其进行格式化和格式化并打印结果,

但是有没有更好的方法来 format__str__() 输入字典中的所有数字时,或者以某种方式将字符串打印出来?

编辑:
我正在寻找一些魔法,例如:

'{format only floats and ignore the rest}'.format(d)

或来自yaml 世界或类似的东西。

【问题讨论】:

  • 看看我更新的解决方案,可能就是你想要的。

标签: python string printing dictionary format


【解决方案1】:

您可以使用round 将浮点数舍入到给定的精度。要识别浮点数,请使用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}

【讨论】:

  • 我一直喜欢单行字,我不知道给你一本字典的{}糖。
  • @Ali 这个叫字典理解,是在py2.7中引入的。
  • Python 3 重命名 dict.iteritems -> dict.items
【解决方案2】:

要将浮点数转换为两位小数,请执行以下操作:

a = 3.141592
b = float("%.2f" % a) #b will have 2 decimal places!
你也可以这样做:
b = round(a,2)

所以要美化你的字典:

newdict = {}
for x in d:
    if isinstance(d[x],float):
        newdict[x] = round(d[x],2)
    else:
        newdict[x] = d[x]

你也可以这样做:

newdict = {}
for x in d:
    if isinstance(d[x],float):
        newdict[x] = float("%.2f" % d[x])
    else:
        newdict[x] = d[x]

虽然推荐第一个!

【讨论】:

  • 我认为您的意思类似于if isinstance(d[x],float):。不管。另一个问题是这会改变正在处理的字典中的值——可能是不可取的。
  • 哦,是的,对不起,这正是我的意思。我做了一个编辑检查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2014-12-15
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多