python - 如果符合特定条件,如何从文本文件中查找列中的值总和

标签 python python-3.x text input output

我在尝试将文本文件中的列中的某些值加在一起时遇到了一些问题。我的文本文件如下所示:

e320,2/3/5,6661,c120,A,6661
e420,6/5/3,16916,c849,A,24323
e432,6/5/3,6962,c8429,A,4324
e430,6/5/3,4322,c8491,A,4322
e32042,2/3/5,13220,c1120,A,13220
e4202,6/5/3,4232,c8419,E,4232

我想找到最后一列值的总和,在数组中提供第三列(最终总数)等于最后一列。 (支付的金额。)。仅当第五列的(状态)等于“E”且最终总计 == 支付金额时,才应找到所有最后一列值的总和。

到目前为止我的代码是:

data = open("paintingJobs.txt", "r")
info=data.readlines()
data.close
totalrev=0
for li in info:
    status=li.split(",")[4]
    finaltotal=int(li.split(",")[2])
    amountpaid=int(li.split(",")[5])
    if amountpaid == finaltotal:
        revenue=True
        if status == "A" and revenue == True:
            totalamountpaid = li.split(",")[5]
            total = (sum(totalamountpaid))
            print("The total revenue is")
            print(total)

我想要的输出是:

The total revenue is
28435

总数应等于 28435,即 6661+4322+13220+4232=28435(status 等于“A”且 finaltotal=amountpaid 时总收入的总和。)

我不断收到“TypeError:不支持的操作数类型 +:'int' 和 'str'”。我正在使用 Python 3.4.3 和一个完整的 Python 新手。任何帮助将不胜感激。

最佳答案

试试这个。

total = (sum(totalamountpaid)) 

total = (sum(map(int,totalamountpaid.split(',')))) 

从字符串映射中拆分每个数字,将字符串转换为 int。然后总结一下。

关于python - 如果符合特定条件,如何从文本文件中查找列中的值总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36662150/

相关文章:

CSS图像悬停改变文本的颜色

Python 相当于 Perl 时间戳

python - matplotlib.scatter 颜色参数不接受 numpy 数组

python - 有没有办法在@before.request中设置cookie?

python - 如何对假设策略实现相对约束?

java - 在 eclipse-rcp/swt 中创建多个相同的文本验证监听器

c# - 如何在 C# 中处理大文本?

python - 查找目录的最后更新时间(包括所有级别的子文件夹)

python - 如何使用套接字从服务器向客户端发送消息

python - Pyside2 我怎样才能移动盒子?