Python,在输出中将所有浮点数打印到小数点后两位

发布于 2024-08-17 15:57:19 字数 230 浏览 4 评论 0原文

我需要输出 4 个不同的浮点数到小数点后两位。

这就是我的:

print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l'

非常不干净,而且看起来很糟糕。有没有办法让输出'%.2f'中出现任何浮动?

注意:使用Python 2.6。

I need to output 4 different floats to two decimal places.

This is what I have:

print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l'

Which is very unclean, and looks bad. Is there a way to make any float in that out put '%.2f'?

Note: Using Python 2.6.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

番薯 2024-08-24 15:57:19

好吧,我至少会按如下方式清理它:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)

Well I would atleast clean it up as follows:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)
月亮邮递员 2024-08-24 15:57:19

格式字符串语法。

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

输出将是:

'3.14, kg=6.28, lb=9.42, gal=12.57'

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'
止于盛夏 2024-08-24 15:57:19

如果您只想将值转换为漂亮的字符串,请执行以下操作:

twodecimals = ["%.2f" % v for v in vars]

或者,您也可以打印出问题中的单位:

vars = [0, 1, 2, 3] # just some example values
units = ['kg', 'lb', 'gal', 'l']
delimiter = ', ' # or however you want the values separated

print delimiter.join(["%.2f %s" % (v,u) for v,u in zip(vars, units)])
Out[189]: '0.00 kg, 1.00 lb, 2.00 gal, 3.00 l'

第二种方法允许您轻松更改分隔符(制表符、空格、换行符等) ) 轻松满足您的需求;分隔符也可以是函数参数,而不是硬编码。

编辑:要使用“名称=值”语法,只需更改列表理解中的按元素操作即可:

print delimiter.join(["%s = %.2f" % (u,v) for v,u in zip(vars, units)])
Out[190]: 'kg = 0.00, lb = 1.00, gal = 2.00, l = 3.00'

If you just want to convert the values to nice looking strings do the following:

twodecimals = ["%.2f" % v for v in vars]

Alternatively, you could also print out the units like you have in your question:

vars = [0, 1, 2, 3] # just some example values
units = ['kg', 'lb', 'gal', 'l']
delimiter = ', ' # or however you want the values separated

print delimiter.join(["%.2f %s" % (v,u) for v,u in zip(vars, units)])
Out[189]: '0.00 kg, 1.00 lb, 2.00 gal, 3.00 l'

The second way allows you to easily change the delimiter (tab, spaces, newlines, whatever) to suit your needs easily; the delimiter could also be a function argument instead of being hard-coded.

Edit: To use your 'name = value' syntax simply change the element-wise operation within the list comprehension:

print delimiter.join(["%s = %.2f" % (u,v) for v,u in zip(vars, units)])
Out[190]: 'kg = 0.00, lb = 1.00, gal = 2.00, l = 3.00'
听风吹 2024-08-24 15:57:19

使用 f 字符串:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

或者在您的情况下:

print(f'{var1:.2f}, kg = {var1:.2f}, lb = {var2:.2f}, gal = {var3:.2f}, {var4:2f} l'

use f-strings:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

or in your case:

print(f'{var1:.2f}, kg = {var1:.2f}, lb = {var2:.2f}, gal = {var3:.2f}, {var4:2f} l'

所有深爱都是秘密 2024-08-24 15:57:19

如果您正在寻找可读性,我相信这就是代码:

print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
    'kg': var1,
    'lb': var2,
    'gal': var3,
    'l': var4,
}

If you are looking for readability, I believe that this is that code:

print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
    'kg': var1,
    'lb': var2,
    'gal': var3,
    'l': var4,
}
一个人的旅程 2024-08-24 15:57:19

我刚刚发现了 round 函数 - 它在 Python 2.7 中,不确定 2.6 中是否如此。它采用浮点数和 dps 数作为参数,因此 round(22.55555, 2) 给出的结果是 22.56。

I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.

青衫儰鉨ミ守葔 2024-08-24 15:57:19

如果您想要让打印操作自动将浮点数更改为仅显示小数点后两位,请考虑编写一个函数来替换“打印”。例如:

def fp(*args):  # fp means 'floating print'
    tmps = []
    for arg in args:
        if type(arg) is float: arg = round(arg, 2)  # transform only floats
        tmps.append(str(arg))
    print(" ".join(tmps)

使用 fp() 代替 print ...

fp("PI is", 3.14159) ... 代替 ... print "PI is", 3.14159代码>

If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:

def fp(*args):  # fp means 'floating print'
    tmps = []
    for arg in args:
        if type(arg) is float: arg = round(arg, 2)  # transform only floats
        tmps.append(str(arg))
    print(" ".join(tmps)

Use fp() in place of print ...

fp("PI is", 3.14159) ... instead of ... print "PI is", 3.14159

孤城病女 2024-08-24 15:57:19

不是直接按照你想写的方式,不。 Python 的设计原则之一是“显式优于隐式”(请参阅​​import this)。这意味着最好描述您想要的内容,而不是让输出格式取决于某些全局格式设置或其他内容。当然,您可以以不同的方式格式化代码以使其看起来更好:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'

Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文