【问题标题】:Wrong counting while using dictionary replacing multi-if statement使用字典替换多 if 语句时计数错误
【发布时间】:2016-09-23 21:08:21
【问题描述】:

我的目标是在 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 新手,提前谢谢你。

【问题讨论】:

    标签: python counting


    【解决方案1】:

    你的缩进是否正确?以

    开头的块
    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.']
    

    【讨论】:

    • 嗨 101,感谢您的及时回复。缩进问题是由paste.sorry引起的。你的第二个建议解决了我的问题一半。它确实将我的字典值重置为0每次迭代。实际上我仍然需要ipl,gs,gt作为变量,因为我必须将这些变量输入到excel的单元格中.如果我将它们定义为零,我很难在以后的代码中控制它们。我保留了它们,但发现 ipl,gs,gt 始终为 0 而不是 companypool[client] 的值。
    • 我已经在最后添加了变量,希望对您有所帮助。
    • 太棒了。它成功了!谢谢。我发现结果是一样的。(multi-if & dictionary 方法)。我看到了下面的帖子,但似乎没有提高性能。stackoverflow.com/questions/17166074/…
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多