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

Python—如果文件中的两行具有匹配条件,请将这些行中的数字相加,python,Python,假设我有一个文本文件,其中包含以下内容(假设标题是:名称、铅笔数量) 这里最重要的是亚历山大和丽贝卡都有多个条目。目前,我的代码从文件中读取行,然后只输出行,忽略任何多个条目;i、 e.所有条目都是相互独立的(我不确定是否需要将代码放在这里-这只是美学上的一般格式)。相反,我希望它将具有多次出现的任何名称的两个数量相加,并将其输出给用户 例如,输出应该如下所示: Harry 3 Alexander 13 Rebecca 50 Rachel 7 Harve

假设我有一个文本文件,其中包含以下内容(假设标题是:名称、铅笔数量)

这里最重要的是亚历山大和丽贝卡都有多个条目。目前,我的代码从文件中读取行,然后只输出行,忽略任何多个条目;i、 e.所有条目都是相互独立的(我不确定是否需要将代码放在这里-这只是美学上的一般格式)。相反,我希望它将具有多次出现的任何名称的两个数量相加,并将其输出给用户

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

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


谢谢大家!

不要使用列表,而是使用字典。将人名存储为键,将累计总和存储为值

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名称重命名了变量


祝你好运:)

不要使用列表,而是使用字典。将人名存储为键,将累计总和存储为值

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名称重命名了变量

祝你好运:)A在这里很好:

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})
>>dd
defaultdict(,{'Harvey':5,'Alexander':13,'Rebecca':50,'Rachel':7,'Harry':3})
A在这里很好:

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})
>>dd
defaultdict(,{'Harvey':5,'Alexander':13,'Rebecca':50,'Rachel':7,'Harry':3})

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

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

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

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
你也可以试试

file_obj = open('data.txt', 'r')
dic = {}
for line in file_obj:
    arr = line.split(',')[:2]
    if arr[0] in dic:
        dic[arr[0]] += int(arr[1])
    else:
        dic[arr[0]] = int(arr[1])


file_obj.close()
你也可以试试

file_obj = open('data.txt', 'r')
dic = {}
for line in file_obj:
    arr = line.split(',')[:2]
    if arr[0] in dic:
        dic[arr[0]] += int(arr[1])
    else:
        dic[arr[0]] = int(arr[1])


file_obj.close()

非常感谢。我可以问一下“out_content='{}{}\t{}\n.format(out_content,name,age)”行中存在out_content的目的是什么吗?谢谢!我可以问一下,在“out_content='{}{}\t{}\n'.format(out_content,name,age)”这一行中存在out_内容的目的是什么吗?