python-3.x - 尝试在不使用熊猫的情况下从 txt 文件中添加字段的总和
问题描述
我试图从我的程序中获取字段 5 的总和。它打开一个 txt 文件,显示名称、商品、商品价格、销售数量,然后计算该人的总销售额。我似乎不知道如何找到计算总数的总和,然后在程序结束时显示它。
def getTotal():
sum(personTotal)
return total
def main():
print("%-8s %-21s %-6s %10s %14s" % ("Name", "Item", "Price", "Quantity", "Person Total"))
f = open("makewaves.txt", "r")
for line in f:
name, item, price, quantity = line.split(",")
price = float(price)
quantity = int(quantity)
personTotal = float(price) * float(quantity)
total = getTotal
print()
print("%-8s %-21s $%-5.2f %6d %14.2f" % (name, item, price, quantity, personTotal))
print()
print(" Total sales are : " + "$" + str(total))
main()
解决方案
这是您的代码的固定版本。目前尚不清楚您要做什么,total = getTotal
所以我完全删除了它和该getTotal()
功能。
为了获得总销售额,您需要通过在循环外初始化一个累加器变量来运行一个累加器,然后按每个人的递增累加器变量personTotal
:
def main():
print("Name Item Price Quantity Person Total")
sale_string = "\n{:8s} {:21s} ${:5.2f} {:6d} {:14.2f}\n"
total_sales = 0 # initialize an accumulator variable
with open("makewaves.txt", "r") as f:
for line in f:
name, item, price, quantity = line.split(",")
price = float(price)
quantity = int(quantity)
personTotal = price * quantity
total_sales += personTotal # add to the total_sales accumulator
print(sale_string.format(name, item, price, quantity, personTotal))
print("Total sales: ${total_sales}")
if __name__ == "__main__":
main()
我已将您的旧样式字符串格式转换为更好的版本,并且还摆脱了标题格式字符串,因为它不需要是动态的。
请注意,我还更改了您的代码以使用with
块来读取您的文件。该with
块是所谓的上下文管理器,并在退出块后自动关闭文件。
我还添加了if __name__ == "__main__"
模式,这样当您将此脚本作为独立 Python 文件运行时,它会调用该main()
函数,但如果您将此脚本导入另一个 Python 文件,main()
则不会调用该函数自动地。
推荐阅读
- mysql - “无法加载身份验证插件'caching_sha2_password'。找不到特定模块”
- ios - ios按钮仅在点击时显示图像
- php - 在 PHP Server cpanel 中设置启动文件
- java - 使用属性和 excludeAttributes 为 SCIM apis 编辑 json 的通用解决方案
- apache-kafka - Kafka Streams:状态存储分区错误
- c# - C# MongoDB - FindOne 随机记录
- java - GC 运行时应用程序没有响应
- ios - 已发布 iOS 应用程序上的更改语言部分
- javascript - 使用 google plus 登录网站
- javascript - 我想从关键帧开始动画按钮单击