文本fi总计

2024-04-26 00:59:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件的数据与数量的好和坏的产品按性别

Male      100 120 
Female    110 150 

我如何从这个文本文件中计算出两种性别的总数,以便打印出480

下面是我的代码:

def total():
    myFile = open("product.txt", "r")
    for result in myFile:
        r = result.split()            
        print(r[1]+r[2])


total()

它打印出列中的内容,但不添加它们


Tags: 数据代码数量产品defresultopenproduct
3条回答

您需要将每个拆分的文本条目转换为整数,并按如下方式保持运行总数:

def total():
    the_total = 0

    with open("product.txt", "r") as myFile:
        for result in myFile:
            r = result.split()            
            the_total += int(r[1]) + int(r[2])

    return the_total

print(total())

这将显示:

480

使用with将自动为您关闭文件。你知道吗

split的结果是字符串序列,而不是整数序列。
+连接两个字符串。你知道吗

有足够线索的互动示例:

>>> s = "123 456"
>>> ss = s.split()
>>> ss
['123', '456']
>>> ss[0] + ss[1]
'123456'
>>> int(ss[0])
123
>>> int(ss[1])
456
>>> int(ss[0]) + int(ss[1])
579

当你得到意想不到的结果时,打开你的解释器,以交互的方式看问题通常会提供很多线索。你知道吗

正如jornsharpe在评论中提到的,您没有添加前面的值。你知道吗

由于要添加所有内容,请跟踪以前的值并添加新行(全部转换为整数)。将代码更改为:

def total():
    t = 0
    with open("product.txt", "r") as myFile:
        for result in myFile:
            r = result.split()
            t += int(r[1]) + int(r[2])
    return t
print(total()) # 480

既然选择了这个,我正在编辑包括文件关闭。 马丁·埃文斯提到:

Using with will automatically close the file for you.

相关问题 更多 >