在python字典中添加更新值

2024-10-01 07:15:13 发布

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

我有一个文本文件中的以下数据,我们将工作

Oct 26th 01:12 pm
» corwinte: Ashar Delivery (64) to Rhad / Set Fee: 31895 CR  Oct 26th 01:12 pm
» corwinte: Ashar Delivery (32) to Habitat-01 / Set Fee: 15716 CR  Oct 24th 04:37 pm
» Dagon hammersmith: Ashar Delivery (23) to Lus / Set Fee: 11871 CR  Oct 24th 04:33 pm
» Dragon: Ashar Delivery (74) to Enala / Set Fee: 38192 CR  Oct 24th 04:33 pm
» Dagon hammersmith: Ashar Delivery (54) to Enala / Set Fee: 27870 CR  Oct 24th 04:33 pm
» Dragon: Ashar Delivery (45) to Turroth / Set Fee: 23225 CR  Oct 24th 04:33 pm
» Falconner: Ashar Delivery (38) to Ceas / Set Fee: 19612 CR

我只是在学习python,所以这里是我的粗略代码,它并不是我想要它做的所有事情,但是它做了一些事情,有些事情做得不太好

首先,我们对以日期开头的行不感兴趣,所以我们忽略这些。 我想要的是,让代码遍历文本文件,收集所有名称及其credit(CR)值,计算每个名称的百分比,并将总数与名称一起存储

到目前为止,我已经能够问的百分比,收集的名字,并得到所有参赛者的百分比,而不是总数

这是我的密码

inp = input('enter the name of the file to be opened\n') #asks for a file,opens it,a guard to handle misspelled or files that don't exist
try:
    fhand = open(inp)
except:
    print('Are you on medications? there is no',inp)
    exit()
per = input('Enter the percentage you would like to calculate from,percentage of the fees recieved')
perc = float(per)
for line in fhand:
    if not line.startswith('»'): continue
    words = line.rstrip().split() #stripping the right spaces and splitting into words
    feesrecieved = words[-2]
    actam = float(feesrecieved)*perc/100
    print(words[1], actam)

我怎么才能说,给我每个名字的总计算值?也就是说所有的龙拖,所有的达贡拖等等。 谢谢你


Tags: theto名称line事情octcr百分比
1条回答
网友
1楼 · 发布于 2024-10-01 07:15:13

我想我理解你的问题。 我会将它添加到dict中,并在执行过程中更新值

per = input('Enter the percentage you would like to calculate 
from,percentage of the fees recieved')
perc = float(per)
totalFees = {} // create empty dict
for line in fhand:
    if not line.startswith('»'): continue
    words = line.rstrip().split() #stripping the right spaces and splitting into words
    feesrecieved = words[-2]
    actam = float(feesrecieved)*perc/100
    print(words[1], actam)
    totalFees[words[1]] = totalFees.get([words[1], 0) + actam //updating dict

你可以在找到百分比后再加,也可以在最后计算总数

相关问题 更多 >