簡體   English   中英

Python-如果文件中的兩行具有匹配條件,請將這些行中的數字加在一起

[英]Python - If two lines in a file have a matching condition, add the numbers in those lines together

假設我有一個文本文件,例如,包含以下內容(假設標題為:名稱,鉛筆數量)

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

這里最主要的是Alexander和Rebecca都有多個條目。 當前,我的代碼從文件中讀取行,並僅輸出行,而忽略任何多個條目; 也就是說,所有條目都是彼此分開的(我不確定我是否需要將代碼放在此處,這只是美學的通用格式)。 相反,我希望它為出現多次的任何名稱將兩個數量加在一起,然后將其輸出給用戶。

因此,例如,輸出應如下所示:

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

但是我不確定如何精確地添加循環中創建的不同數組中的數字? 也許如果我初始化了一個變量以跟蹤數量,那么可能只對我知道具有匹配條件的變量執行此操作。

謝謝!

defaultdict在這里會很好:

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})

不要使用列表,而應使用字典。 將人員姓名存儲為關鍵字,並將累積總和存儲為值。

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)

注意 :我已使用更多pythonic名稱重命名了變量。

祝好運 :) !

你也可以嘗試

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()

您可能要為此使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM