在 Python3 中打印格式化的浮点列表

new*_*ntu 3 python printing floating-point formatting python-3.x

我正在编写一个执行以下操作的程序:

  1. 采用逗号分隔的多个输入(浮点)
  2. 对列表的所有元素执行计算
  3. 输出一个列表(带两位小数的浮点数)

我编写了以下程序

import math

C = 50.0
H = 30.0
Q = []

D = input("Please input the D-Values\n").split(",")
[float(k) for k in D]
#[int(k) for k in D]

print("D = {}".format(D))

for i in D:
    j = (math.sqrt((2*C*float(i))/H))
    Q.append(j) 


print("The answers are")
print(Q)
print(type(Q[0]))
print("Q = {:.2f}".format(Q))
Run Code Online (Sandbox Code Playgroud)

我在执行这个程序时遇到以下错误

Traceback (most recent call last):
  File "/home/abrar/pythonPrograms/Challange6.py", line 24, in <module>
    print("Q = {:.2f}".format(Q))
TypeError: non-empty format string passed to object.__format__
Run Code Online (Sandbox Code Playgroud)

我试图寻找这个问题的解决方案,但找不到答案。如果不包含 {:.2f},即使用 {},程序运行良好。但是,输出看起来非常混乱。

任何帮助都受到高度赞赏。

hir*_*ist 7

您正在尝试list使用格式字符串格式化 a .2f- 您想要的是格式化float列表中的s 。这是解决此问题的一种方法:

Q = [1.3, 2.4]
print(', '.join('{:.2f}'.format(f) for f in Q))
# 1.30, 2.40
Run Code Online (Sandbox Code Playgroud)

从 python 3.6 开始,这也可以写成:

print(', '.join(f'{q:.2f}' for q in Q))
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建自己的接受格式字符串的类:

class FloatList(list):

    def __init__(self, *args):
        super().__init__(args)

    def __format__(self, format_spec):
        return f'[{", ".join(f"{i:{format_spec}}" for i in self)}]'


fl = FloatList(0.1, 0.33, 0.632)
print(f"{fl:.2f}")  # [0.10, 0.33, 0.63]
Run Code Online (Sandbox Code Playgroud)