You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现从二维数组的子总计计算总合计问题求助

计算商品总合计解决方案

我正在编写Python程序,从receipt.txt文本文件读取商品数据,计算每个商品的子总计(单价×数量)并存储到二维数组prdCalculation中。目前已完成子总计的计算与存储,但不知道如何从该数组中取出所有子总计值并求和得到总合计。

当前代码:

file =  open("receipt.txt")
tempArray = []
prdCalculation = []
for row in file:
    #split
    field = row.split(",")
    prdID = field[0]
    prdName = field[1]
    prdPrice = float(field[2])
    prdQuan = int(field[3])
    #calc
    subtotal  = round(prdPrice*prdQuan, 2)
    #appending into array
    tempArray.append(prdName)
    tempArray.append(prdPrice)
    tempArray.append(prdQuan)
    tempArray.append(subtotal)
    prdCalculation.append(tempArray)
    tempArray = []

#printing the array
for row in prdCalculation:
    for element in row:
        print(element, end=" ")
    print()

解决方法

prdCalculation的每个子列表结构为[商品名, 单价, 数量, 子总计],子总计对应索引为3的元素,直接遍历累加即可,两种实现方式:

方式1:基础循环累加

在现有代码末尾添加以下代码:

# 初始化总合计为0
total = 0.0
# 遍历二维数组的每一行
for item in prdCalculation:
    # 取出每行的子总计并累加
    total += item[3]
# 保留两位小数处理浮点精度问题
total = round(total, 2)
print(f"\n总合计: {total}")

方式2:列表推导式+sum函数(更简洁)

同样在现有代码末尾添加:

# 用生成器表达式取出所有子总计,求和后保留两位小数
total = round(sum(item[3] for item in prdCalculation), 2)
print(f"\n总合计: {total}")

额外优化:文件操作最佳实践

建议使用with语句自动管理文件资源,避免忘记关闭文件,修改后的文件读取部分代码如下:

with open("receipt.txt") as file:
    tempArray = []
    prdCalculation = []
    for row in file:
        #split
        field = row.split(",")
        prdID = field[0]
        prdName = field[1]
        prdPrice = float(field[2])
        prdQuan = int(field[3])
        #calc
        subtotal  = round(prdPrice*prdQuan, 2)
        #appending into array
        tempArray.append(prdName)
        tempArray.append(prdPrice)
        tempArray.append(prdQuan)
        tempArray.append(subtotal)
        prdCalculation.append(tempArray)
        tempArray = []

内容的提问来源于stack exchange,提问作者Dylan Murphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:00:15