猿问

Python:将每一行与字典中的值相加

dict = {'A': 71.07884,

    'B': 110,

    'C': 103.14484,

    'D': 115.08864,

    'E': 129.11552,

    'F': 147.1766,

    'G': 57.05196,

    'H': 137.1412

    }



def search_replace(search, replacement, searchstring):

    p = re.compile(search)

    searchstring = p.sub(replacement, searchstring)

    return (searchstring)



def main():

    with open(sys.argv[1]) as filetoread:

    lines = filetoread.readlines()

    file = ""


    for i in range(len(lines)):

        file += lines[i]


    file = search_replace('(?<=[BC])', ' ', file)


    letterlist = re.split('\s+', file)


    for j in range(len(letterlist)):

        print(letterlist[j])


if __name__ == '__main__':

    import sys

    import re

    main()

我的程序打开一个文件并在 B 或 C 之后拆分字母文本。


该文件如下所示:


ABHHFBFEACEGDGDACBGHFEDDCAFEBHGFEBCFHHHGBAHGBCAFEEAABCHHGFEEEAEAGHHCF

现在我想用 dict 中的值对每一行求和。


例如:


AB = 181.07884

HHFB = 531.4590000000001

等等。


我不知道如何开始。非常感谢您的所有回答。


慕姐4208626
浏览 179回答 3
3回答

慕斯709654

您已经完成了大部分工作!你错过的只是每个子串的总和。由于子字符串可以更频繁地出现,我将只进行一次求和,并存储在 dict 中遇到的每个子字符串的值(以及您上面的 dict 用于字母与值的关系,我将其重命名为 mydict 以避免关键字混淆) :snippets = {}for snippet in letterlist:&nbsp; &nbsp; if snippet not in snippets:&nbsp; &nbsp; &nbsp; &nbsp; value = 0&nbsp; &nbsp; &nbsp; &nbsp; for s in snippet:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value += mydict.get(s)&nbsp; &nbsp; &nbsp; &nbsp; snippets[snippet] = valueprint(snippets)这给了我一个输出{'AB': 181.07884,&nbsp;'HHFB': 531.4590000000001,&nbsp;'FEAC': 450.5158,&nbsp;'EGDGDAC': 647.6204,&nbsp;'B': 110,&nbsp;'GHFEDDC': 803.8074,&nbsp;'AFEB': 457.37096,&nbsp;'HGFEB': 580.4852800000001,&nbsp;'C': 103.14484,&nbsp;'FHHHGB': 725.6521600000001,&nbsp;'AHGB': 375.272,&nbsp;'AFEEAAB': 728.64416,&nbsp;'HHGFEEEAEAGHHC': 1571.6099199999999,&nbsp;'F': 147.1766}

炎炎设计

尝试简化事情...鉴于您已经有一个字符串s和一个字典d:ctr = 0temp = ''for letter in s:&nbsp; &nbsp; ctr += d[letter]&nbsp; &nbsp; temp += letter&nbsp; &nbsp; if letter in 'BC':&nbsp; &nbsp; &nbsp; &nbsp; print(temp, ctr)&nbsp; &nbsp; &nbsp; &nbsp; ctr = 0&nbsp; &nbsp; &nbsp; &nbsp; temp = ''在您提供的情况下:s = "ABHHFBFEACEGDGDACBGHFEDDCAFEBHGFEBCFHHHGBAHGBCAFEEAABCHHGFEEEAEAGHHCF"d = {'A': 71.07884,'B': 110,'C': 103.14484,'D': 115.08864,'E': 129.11552,'F': 147.1766,'G': 57.05196,'H': 137.1412}你得到结果(打印到终端):>>> ('AB', 181.07884)('HHFB', 531.4590000000001)('FEAC', 450.5158)('EGDGDAC', 647.6204)('B', 110)('GHFEDDC', 803.8074)('AFEB', 457.37096)('HGFEB', 580.4852800000001)('C', 103.14484)('FHHHGB', 725.6521600000001)('AHGB', 375.272)('C', 103.14484)('AFEEAAB', 728.64416)('C', 103.14484)('HHGFEEEAEAGHHC', 1571.6099199999999)
随时随地看视频慕课网APP

相关分类

Python
我要回答