首页 > 解决方案 > 有没有办法根据文本文件中某个位置的内容来累加金额?

问题描述

我努力了

totalValue = 0 bagChecked = 0

for x in range(len(volunteerList)):
    record = volunteerList[x]

    if record[1] == "1 pence":
        amount = 1.00
    elif record[1] == "2 pence":
        amount = 1.00
    elif record[1] == "5 pence":
        amount = 5.00
    elif record[1] == "10 pence":
        amount = 5.00
    elif record[1] == "20 pence":
        amount = 10.00
    elif record[1] == "50 pence":

        amount = 10.00
    elif record[1] == "1 pound":
        amount = 20.00
    else:
        amount = 20.00

    totalValue = totalValue + amount
    bagsChecked = bagsChecked + 1

    print("Bags checked: ",bagsChecked)
    print("Total Value: ",totalValue)'''

有没有办法可以解决这个问题,以便它显示准确的托运行李数量和总值。

标签: pythonif-statement

解决方案


我不能确定这会运行,因为我不知道你的数据是什么样的,但你可以尝试这样的事情:

total_value = 0
total_bags = 0

for rec in volunteerList:

    if "pence" in rec[1]:
        total_value += float(rec[1].split[' '][0])
    if "pound" in rec[1]:
        total_value += 20 * float(rec[1].split[' '][0])

    total_bags += 1

    print("Bags checked: {}".format(total_bags))
    print("Total Value: {}".format(total_value))

这假设每个条目volunteerList都是一个包含“便士”或“英镑”的字符串。然后我们拆分字符串并保留我们的计数的数字部分。


推荐阅读