Python如果文件中的两行具有匹配条件,则将这些行中的数字相加

2024-05-13 19:23:57 发布

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

例如,假设我有一个文本文件,其中包含以下内容(假设标题是:Name,Amount of pencils)

Harry,3,
Alexander,4,
Rebecca,39,
Rachel,7,
Alexander,9,
Harvey,5,
Rebecca,11,

这里最重要的是亚历山大和丽贝卡都有多个条目。目前,我的代码从文件中读取行,然后只输出行,忽略任何多个条目;也就是说,这些条目都是相互独立的(我不确定是否需要将代码放在这里-这只是为了美观而设置的常规格式)。相反,我希望它将具有多次出现的任何名称的两个数量相加,并将其输出给用户。你知道吗

例如,输出应该如下所示:

Harry        3
Alexander    13
Rebecca      50
Rachel       7
Harvey       5

我觉得我遗漏了一些明显的东西(如果是的话,我很抱歉),但是我该如何检查行是否有匹配的名称,如果有,将这些数字加在一起作为最终输出?创建一个新文件来存储这些新值会更容易吗? 目前,我的思路是:

namesInFile = []
with open("Pencils.txt","r") as file:
    for line in file:
        pencilArr = line.split(",")
        namesInFile.append(pencilArr[0])

       if namesInFile.count(pencilArr[0]) > 0:
         do something

但我不确定如何准确地从循环中创建的不同数组中添加数字?也许如果我初始化一个变量来跟踪数量,那么只有那些我知道有匹配条件的变量才有可能这样做。你知道吗

谢谢你!你知道吗


Tags: 代码名称数量line条目数字filerebecca
3条回答

不要用列表,用字典代替。将人名存储为键,将累计和存储为值。你知道吗

names_in_file = {}
with open("Pencils.txt","r") as file:
    for line in file:
        pencil_list = line.split(",")
        names_in_file[pencil_list[0]] = names_in_file.get(pencil_list[0], 0) + int(pencil_list[1])

然后,在读取完文件之后,通过在已形成的字典中处理键和值来形成输出文件。你知道吗

out_content = ''
for name, age in names_in_file.iteritems():
    out_content = '{}{}\t{}\n'.format(out_content, name, age)
with out_file as open('path_to_out_file', "wt"):
    out_file.write(out_content)

注意:我用更多python名称重命名了变量。你知道吗

祝你好运:)!

在这里^{}会很好:

import collections as co

dd = co.defaultdict(int)
with open("Pencils.txt","r") as fin:
    for line in fin:
        name,amount,blank = line.split(',')
        dd[name] += int(amount)

结果:

>>> dd
defaultdict(<type 'int'>, {'Harvey': 5, 'Alexander': 13, 'Rebecca': 50, 'Rachel': 7, 'Harry': 3})

对此,您可能希望使用Python字典而不是列表。您可能想了解dictionaries,但这是如何使用一个实现它的:

name_pencil_dict = {}    # Create the dictionary
with open("Pencils.txt","r") as file:
for line in file:
    pencilArr = line.split(",")
    name = pencilArr[0]
    num_pencils = pencilArr[1]

    if name not in list(name_pencil_dict.keys):
        # Name not found, create new dictionary entry, initialize num pencils to zero
        name_pencil_dict[name] = 0

    # Add the number of pencils to the name's dictionary value
    name_pencil_dict[name] += num_pencils

相关问题 更多 >