【问题标题】:Python - sum variables from a text filePython - 对文本文件中的变量求和
【发布时间】:2014-05-10 09:49:10
【问题描述】:

以下是我目前所拥有的:我知道在将金额更改为浮点数后,我需要对文件 numberGood.txt 中的数字进行合计,但这些数字没有变量名,即。 num1, num2 因为程序不知道文件的数量。我已经用 while 循环解决了这个问题,但是如何获得所有数字的总和?

*numberGood.txt 是我需要在我的程序中求和的各种整数的列表。

如果有人能解释和/或给我一个例子,我将非常感激。

def main(): 
    goodNum = open("numberGood.txt",'r')
    input("Enter file name.")
    line = goodNum.readline()
    while line != "":
    amount = float(line)
    print(format(amount, '.1f'))
    line = goodNum.readline()
    print("The total is: ", amount)
    goodNum.close()
main()

【问题讨论】:

    标签: python variables while-loop sum


    【解决方案1】:

    使用sum():

    with open("numberGood.txt") as f:
        print(sum(float(line) for line in f))
    

    演示:

    $ cat numberGood.txt 
    10.01
    19.99
    30.0
    40
    $ python3
    >>> with open("numberGood.txt") as f:
    ...     print(sum(float(line) for line in f))
    ... 
    100.0
    

    【讨论】:

      【解决方案2】:

      您可以将它们添加到列表中,然后返回列表的总和,如下所示:

      def main(): 
          goodNum = open("numberGood.txt",'r')
          lst = []
          for line in goodNum:
              lst.append(float(line))
              print(format(lst[-1], '.1f'))
          print("The total is: ", sum(lst))
          goodNum.close()
      
      main()
      

      【讨论】:

        猜你喜欢
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多