代码之家  ›  专栏  ›  技术社区  ›  new2Ubuntu

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

  •  4
  • new2Ubuntu  · 技术社区  · 8 年前

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

    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))
    

    执行此程序时,我面临以下错误

    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__
    

    我试图寻找这个问题的解决办法,但找不到答案。如果不包括{:.2f},即使用{},则程序工作正常。然而,输出看起来非常混乱。

    非常感谢您的帮助。

    2 回复  |  直到 8 年前
        1
  •  10
  •   hiro protagonist    7 年前

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

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

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

    print(', '.join(f'{q:.2f}' for q in Q))
    

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

    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]
    
        2
  •  2
  •   user2314737    8 年前

    您正在尝试格式化列表,但您需要格式化此列表的元素,因此需要使用 *Q 代替 Q (the * 操作员“解包”列表)

    这里有一个解决方案:

    fmtL = "Q = " + ', '.join(["{:.2f}"]*len(Q))
    print(fmtL.format(*Q))
    Q = 1.83, 2.58, 3.16