如何从文件中读取浮点数到列表中?

How to read floats onto a list from a file?

提问人:DimTriptamine 提问时间:11/15/2023 最后编辑:mkrieger1DimTriptamine 更新时间:11/15/2023 访问量:37

问:

我被要求创建一个程序,将金额(费用)读取到列表中。将它们读入列表后,计算并打印:

  • 总美元AMT
  • 文件中有多少个收据
  • 平均
  • 最大 AMT
  • 收据列表从小到大。

我有一个代码的粗略草稿,但是我编写程序的方式是程序存储的有限数量的收据。总 amt、平均值和最大金额很容易计算,正如您将在代码中看到的那样。我的问题是将费用读取到一个清单中,并弄清楚有多少收据是合适的,因为我应该有任意数量的收据。 如果我必须删除所有代码并从头开始,那么这就是我必须要做的。 我在这个程序中所做的一切我都理解。我觉得我没有看到我应该做什么的大局。

我注释掉了一些代码,因为我宁愿在创建文件并将信息写入文件之前专注于获取正确的代码。

def main():
    #expense_file = open("expenses.txt", "w")
    total1 = 0
    receipt1 = []
    enter_expense = float(input("Enter expense: $"))
    while enter_expense > 0:
        receipt1.append(format(enter_expense, ".2f"))
        total1 += enter_expense
        enter_expense = float(input("Enter expense: $"))
    #expense_file.write(str(receipt1))
    print("Your total for receipt #1 is: $", format(total1, ".2f"), "\n" +
          "Receipt #1: ", receipt1)


    total2 = 0
    receipt2 = []
    enter_expense = float(input("Enter expense: $"))
    while enter_expense > 0:
        receipt2.append(format(enter_expense, ".2f"))
        total2 += enter_expense
        enter_expense = float(input("Enter expense: $"))
    #expense_file.write(str(receipt2))
    print("Your total for receipt #2 is: $", format(total2, ".2f"), "\n" +
          "Receipt #2: ", receipt2)


    total3 = 0
    receipt3 = []
    enter_expense = float(input("Enter expense: $"))
    while enter_expense > 0:
        receipt3.append(format(enter_expense, ".2f"))
        total3 += enter_expense
        enter_expense = float(input("Enter expense: $"))
    #expense_file.write(str(receipt3))
    print("Your total for receipt #3 is: $", format(total3, ".2f"), "\n" +
          "Receipt #3: ", receipt3)
    
    total_receipt = receipt1 + receipt2 + receipt3
    total = total1 + total2 + total3
    average = total / len(total_receipt)
    print("Total expense: $", total)
    print("Average expense: $", average)
    print("Minimum expense: $", min(total_receipt), "and maximum expense: $", max(total_receipt))
    total_receipt.sort()
    print("Sorted list of expenses: ", total_receipt)

#    expense_file.close()


main()
python 列表 文件 while-loop

评论


答: 暂无答案