【问题标题】:Print tuple of Decimals without the label "Decimal"打印不带“十进制”标签的十进制元组
【发布时间】:2016-12-23 10:38:12
【问题描述】:

我有一个Vector 类如下:

class Vector(object):

    def __init__(self, coordinates):
        self.coordinates = tuple([Decimal(x) for x in coordinates])

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

如果我运行下面的代码...

v1 = Vector([1,1])
print v1

...我明白了

Vector: (Decimal('1'), Decimal('1'))

如何摆脱“十进制”标签? 输出应如下所示:

Vector: (1, 1)

【问题讨论】:

  • Python Decimal to String的可能重复
  • 我知道 str() 方法,但只是将它应用于元组并没有删除标签“十进制”。列表理解中的 str() 和 join() 方法的组合解决了我的问题。

标签: python list decimal pretty-print


【解决方案1】:

在小数点周围添加str() 有效:

from __future__ import print_function
from decimal import Decimal

class Vector(object):

    def __init__(self, coordinates):
        self.coordinates = tuple([Decimal(x) for x in coordinates])

    def __str__(self):
        return 'Vector: ({})'.format(', '.join(str(x) for x in self.coordinates))

v1 = Vector([1,1])
print(v1)

输出:

Vector: (1, 1)

【讨论】:

  • 是的,意识到了这一点。改进,
【解决方案2】:

只需调用str 函数:

import decimal
d = decimal.Decimal(10)
d
Decimal('10')
str(d)
'10'

对于您的代码:

def __str__(self):
    return 'Vector: {}'.format(map(str, self.coordinates))

【讨论】:

  • 永远不要直接调用双下划线方法。此代码应为str(d)
  • 这不是 OP 想要的输出:它有方括号而不是圆括号,并且在坐标周围有不需要的引号。而在 Python 3 中,map 返回的是地图对象,而不是列表,因此输出会更加难以理解。
猜你喜欢
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多