应用"%。1f"到多个变量

时间:2015-03-28 18:49:47

标签: python python-3.x floating-point-precision

刚刚开始上课,练习是学习如何使用round(x, n)截断floats

唯一的问题是,它没有。我发现了如何在线使用%.1f,但是有没有办法将它应用于多个变量而不必一遍又一遍地写它?

我设置如下:

a = float(input("a:"))
b = float(input("b:"))
c = float(input("c:"))
d = float(input("d:"))
e = float(input("e:"))

sum = a + b + c + d + e
average = sum/5

print ("The sum of ", "%.1f" % (a), ", ", "%.1f" % (b), ",", "%.1f" % (c), ", ", "%.1f" % (d), ", and ", "%.1f" % (e), "is ", "%.1f" % (sum), ". Meanwhile, the average is ", "%.2f" % (average), ".")

有没有办法在不必写这么多的情况下应用%.1f

编辑:感谢所有帮助过的人。我发现onurgüngör最适合我正在寻找的东西,但我从每个人的输入中学到了很多东西。欣赏它。

4 个答案:

答案 0 :(得分:2)

我不确定是否有办法直接做你想做的事情。但是,你可以尝试双格式并使用更新的风格。

str = "values: {0}, {0}, {0}, {0}, {0}".format("{:.2f}");
str = str.format(a, b, c, d, e);

答案 1 :(得分:2)

您可以方便地将这些值存储在列表中。例如:

names = list("abcde")
values = [ float(input(n + ":")) for n in names ]
fvalues = ', '.join("{:.1f}".format(v) for v in values)

fvalues可能看起来像:

'4.0, 4.4, 4.4, 2.3, 4.4'

这些值也可以按列表形式计算:

total = sum(values)
avg = total / len(values)

如果您希望更多面向调试的值列表格式,请执行以下操作:

dvalues = '  '.join("{}: {:.1f}".format(n,v) for n,v in zip(names,values))

收率:

'a: 4.0  b: 4.4  c: 4.4  d: 2.3  e: 4.4'

答案 2 :(得分:1)

我想你想要这样的东西。

n = 10
vars = []
for i = range(1, n+1):
  vars.append(float(input("%d: " % i)))

vars_sum = sum(vars)
average = vars_sum/5

str = "The sum of "
for var in vars[:-1]:
  str += "%.1f, " % var
str += "and " + "%.1f" % vars[-1:][0] + " is %.1f." % vars_sum
str += " Meanwhile, the average is %.2f." % average
print(str)

答案 3 :(得分:0)

这里使用字符串格式很有用。构建格式化程序字符串,然后将其应用于多个值。

one_digit_float = "{:.1f}"

responses = dict()
for varname in ['a','b','c','d','e']:
    responses[varname] = input(varname+": ")
# this is equivalent to:
# # responses = {varname: input(varname+": ") for varname in 'abcde'}
print "Variables are " + ', '.join(varname + ": " + one_digit_float.format(val) for varname,val in responses.items())