Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印不带“Decimal”标签的小数元组_Python_List_Decimal_Pretty Print - Fatal编程技术网

Python 打印不带“Decimal”标签的小数元组

Python 打印不带“Decimal”标签的小数元组,python,list,decimal,pretty-print,Python,List,Decimal,Pretty Print,我有一个向量类,如下所示: 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])

我有一个向量类,如下所示:

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
…我明白了

向量:十进制'1',十进制'1' 我怎样才能去掉“十进制”标签? 输出应该如下所示:

向量:1,1 只需调用str函数:

import decimal
d = decimal.Decimal(10)
d
Decimal('10')
str(d)
'10'
对于您的代码:

def __str__(self):
    return 'Vector: {}'.format(map(str, self.coordinates))
在小数点附近添加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)

永远不要直接调用双下划线方法。这段代码应该是strd。这并不是OP想要的输出:它有方括号而不是圆括号,并且在co-ords周围有不需要的引号。在Python3中,map返回一个map对象,而不是一个列表,因此输出将更加难以理解。列表理解中str和join方法的组合解决了我的问题。是的,我意识到了这一点。改进,