使用字典替换 multi-if 语句时计数错误

Wrong counting while using dictionary replacing multi-if statement

我的目标是计算 Excel 中指定公司的报价。

我以前用过很多if语句来做计数工作。 代码如下

ipl=gs=gt=0
for file in glob.glob('*.xlsm'):
    wb=load_workbook(file,data_only=True)
    ws=wb["Tim"]
    client=ws['B2'].value

    if client=='Injection Parts Ltd.':
        ipl+=1
    if client=='Gulf Sample Ltd':
        gs+=1
    if client=='Great test Ltd.':
        gt+=1

以上有效。

考虑到if语句有20多个,需要很长时间才能完成检查,我使用了如下字典

ipl=gs=gt=0
for file in glob.glob('*.xlsm'):
    wb=load_workbook(file,data_only=True)
    ws=wb["Tim"]
    client=ws['B2'].value

companypool = {'Injection Parts Ltd.':ipl,
            'Gulf Sample Ltd':gs,
            'Great test Ltd.':gt}

if client in companypool:
    print(companypool[client])
    print(client)
    companypool[client]+=1

结果companypool[client]一直为0,计数失败

代码有错吗?

我是 Python 的新手,在此先感谢您。

你的缩进正确吗?以

开头的区块
if client in companypool:

看起来没有正确缩进。还有那行

companypool = {'Injection Parts Ltd.':ipl,
    'Gulf Sample Ltd':gs,
    'Great test Ltd.':gt}

将在每次迭代时将您的字典值重置为 0。将其移动到脚本的开头。

总体看起来像你想要的:

companypool = {
    'Injection Parts Ltd.': 0,
    'Gulf Sample Ltd': 0,
    'Great test Ltd.': 0,
}

for file in glob.glob('*.xlsm'):
    wb = load_workbook(file, data_only=True)
    ws = wb["Tim"]
    client = ws['B2'].value

    if client in companypool:
        print(companypool[client])
        print(client)
        companypool[client] += 1

ipl = companypool['Injection Parts Ltd.']
gs  = companypool['Gulf Sample Ltd']
gt  = companypool['Great test Ltd.']