You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python统计嵌套列表子串时for循环最后一个elif不生效问题

问题原因

代码使用了互斥的if...elif串行判断逻辑,而你每个子列表中同时存在多个待统计的sub字符串:只要前面任意一个条件匹配成功,后续所有elif分支都会直接跳过,不会再执行。
比如示例中的['sub15', 'sub17']子列表,'sub15' in sampleList首先匹配成功,执行sh6 +=1后直接跳出整个判断逻辑,完全不会检查sub17是否存在,因此sub17的计数始终为0。

修复方案

方案1:改为独立if判断

将所有elif替换为独立的if,让每个sub字符串的判断逻辑都独立执行,互不干扰:

for pos, sampleList in lst: 
    if 'sub10' in sampleList: 
        sh1 += 1
    if 'sub11' in sampleList: 
        sh2 += 1
    if 'sub12' in sampleList: 
        sh3 += 1
    if 'sub13' in sampleList: 
        sh4 += 1
    if 'sub14' in sampleList: 
        sh5 += 1
    if 'sub15' in sampleList: 
        sh6 += 1
    if 'sub16' in sampleList: 
        sh7 += 1
    if 'sub17' in sampleList: 
        sh8 += 1

方案2:使用字典批量计数(更易扩展)

如果后续需要新增统计项,不用新增变量和判断分支,代码更简洁易维护:

# 初始化待统计的sub字符串
target_subs = ['sub10', 'sub11', 'sub12', 'sub13', 'sub14', 'sub15', 'sub16', 'sub17']
count = {sub:0 for sub in target_subs}

for pos, sampleList in lst:
    for sub in sampleList:
        if sub in count:
            count[sub] += 1

# 取值示例:count['sub10'] 即为sub10的统计结果

内容的提问来源于stack exchange,提问作者pythonbeginner44

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:57:04