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

Python循环处理列表遇IndexError,如何为越界索引输出‘no value’?

解决索引越界并填充默认值的方案

你的问题核心是当遍历到列表末尾时,剩余元素不足4个,导致访问超出列表范围的索引抛出错误。我们可以通过两种直观的方式处理这个问题:

方法一:添加索引越界判断

直接在访问每个索引前先检查是否越界,不存在就返回no value。同时我调整了字典的键顺序,和你期望的输出保持一致:

x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
result_list = []
i = 0
while i < len(x):
    # 逐个判断索引是否存在,不存在则用默认值填充
    wife_name = x[i] if i < len(x) else 'no value'
    wife_code = x[i+1] if (i+1) < len(x) else 'no value'
    husband_name = x[i+2] if (i+2) < len(x) else 'no value'
    husband_code = x[i+3] if (i+3) < len(x) else 'no value'
    
    current_pair = {
        'wife_list': wife_name,
        'wife_code': wife_code,
        'husband_list': husband_name,
        'husband_code': husband_code
    }
    result_list.append(current_pair)
    i += 4
print(result_list)

方法二:先补全列表再分组

先把原列表补全到长度为4的倍数,不足的部分用no value填充,这样遍历的时候就完全不用担心越界问题了:

x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
# 计算需要补充的默认值数量
pad_length = (4 - len(x) % 4) % 4
x += ['no value'] * pad_length

result_list = []
# 按步长4遍历列表
for i in range(0, len(x), 4):
    current_pair = {
        'wife_list': x[i],
        'wife_code': x[i+1],
        'husband_list': x[i+2],
        'husband_code': x[i+3]
    }
    result_list.append(current_pair)
print(result_list)

输出结果

两种方法都能得到你期望的输出:

[{'wife_list': 'ann', 'wife_code': 'D4B3', 'husband_list': 'richard', 'husband_code': 'A4N5'}, {'wife_list': 'lily', 'wife_code': 'M3L1', 'husband_list': 'david', 'husband_code': 'P4N5'}, {'wife_list': 'bea', 'wife_code': 'S3B2', 'husband_list': 'no value', 'husband_code': 'no value'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:01:14