我阅读了很多关于SE的讨论,但是仍然找不到合适的讨论。
我想用相同的数字绘制一些不同长度的数字。
例如,我有:12.345678
,1.2345678
。现在,由于必须将它们与错误一起绘制,因此我希望每个人都有不同的格式,以使它们有意义。
因此,我想用可变数量的小数来绘制它们。就我而言,绘制情节毫无意义,23.45678+/-1.23456
但更好23.4+/-1.2
。另一方面,我需要1.234567+/-0.034567
变为1.23+/-0.03
。
所以,比方说,我想以固定的宽度绘制所有数字,总共可能是3位数字加上逗号。我应该使用'%1.1f' %num
,但找不到正确的方法。我怎样才能做到这一点?
我建议定义一个类,该类解释字符串格式化程序以提供所需的内容。
在该类内部,您可以确定浮点数的整数部分的长度,并使用该长度来定义适当的字符串格式。
简而言之,该类将创建一个格式化程序,例如,'{:4.1f}'
如果您的输入是12.345
(因为小数点分隔符之前有两位数字)和{:4.2f}
如果您输入了它1.2345
(因为您的输入十进制分隔符前只有一位数字)。提供了总位数(4
在此示例中)作为输入。
新的格式设置为:{:nQ}
其中n
是位的总数(因此在上面的示例中,您将指定{:4Q}
获取所需的输出。
这是代码:
import math
class IntegerBasedFloat(float):
def __format__(self, spec):
value = float(self)
# apply the following only, if the specifier ends in Q
# otherwise, you maintain the original float format
if spec.endswith('Q'):
# split the provided float into the decimal
# and integer portion (for this math is required):
DEC, INT = math.modf(value)
# determine the length of the integer portion:
LEN = len(str(abs(int(INT))))
# calculate the number of available decimals
# based on the overall length
# the -1 is required because the separator
# requires one digit
DECIMALS = int(spec[-2]) - LEN - 1
if DECIMALS < 0:
print 'Number too large for specified format'
else:
# create the corresponding float formatter
# that can be evaluated as usual:
spec = spec[-2] + '.' + str(DECIMALS) + 'f'
return format(value, spec)
DATA = [12.345, 2.3456, 345.6789]
print '{:4Q}'.format(IntegerBasedFloat(DATA[0]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[1]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[2]))
print 'This is a "custom" float: {:5Q} and a "regular" float: {:5.3f}'.format(IntegerBasedFloat(12.3456),12.3456)
输出应为:
12.3
2.35
346
This is a "custom" float: 12.35 and a "regular" float: 12.346
这个答案的灵感源于:
-在python中将数字分为整数和小数部分
-为字符串格式添加自定义转换类型
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句