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

如何在Python类中定义默认列表,避免缺失索引引发报错

解决Python类中列表参数长度不足引发的索引错误

当前代码中plot方法直接通过索引[0]和[1]获取点的x、y坐标,但如果传入的点列表长度不足2(比如b1=[2]),会触发IndexError。以下是几种可行的解决方式,核心思路是确保每个点都能提供x、y两个坐标值:

方案1:初始化阶段补全参数的默认值

在__init__方法中检查每个点参数的长度,若不足2则补充默认值(这里用0,可根据需求修改):

class Points():
    def __init__(self, a1, b1, c1, d1):
        # 确保每个点都是长度≥2的列表,不足则补默认值
        self.a1 = a1 if len(a1) >= 2 else a1 + [0]
        self.b1 = b1 if len(b1) >= 2 else b1 + [0]
        self.c1 = c1 if len(c1) >= 2 else c1 + [0]
        self.d1 = d1 if len(d1) >= 2 else d1 + [0]

    def plot(self):
        xs = [self.a1[0], self.b1[0], self.c1[0], self.d1[0]]                           
        ys = [self.a1[1], self.b1[1], self.c1[1], self.d1[1]] 
        print(xs)
        print(ys)                           
        colors = ['c','m','b','y']

# 调用时b1=[2]会被自动补全为[2, 0]
a1 = Points([1,2], [2], [3,4], [4,5])
a1.plot()

方案2:设置默认参数并处理长短列表

给每个点参数设置默认的长度为2的列表,同时兼容传入短列表的情况,过长列表则截取前两个元素:

class Points():
    # 默认每个点为[0, 0],可覆盖
    def __init__(self, a1=[0,0], b1=[0,0], c1=[0,0], d1=[0,0]):
        # 处理参数:短列表补0,长列表截前两位
        self.a1 = a1[:2] + [0]*(2 - len(a1))
        self.b1 = b1[:2] + [0]*(2 - len(b1))
        self.c1 = c1[:2] + [0]*(2 - len(c1))
        self.d1 = d1[:2] + [0]*(2 - len(d1))

    def plot(self):
        xs = [self.a1[0], self.b1[0], self.c1[0], self.d1[0]]                           
        ys = [self.a1[1], self.b1[1], self.c1[1], self.d1[1]] 
        print(xs)
        print(ys)                           
        colors = ['c','m','b','y']

a1 = Points([1,2], [2], [3,4], [4,5])
a1.plot()

方案3:在plot方法中安全获取坐标

不修改初始化逻辑,而是在访问坐标时做容错处理,避免索引错误:

class Points():
    def __init__(self, a1, b1, c1, d1):
        self.a1 = a1
        self.b1 = b1
        self.c1 = c1
        self.d1 = d1

    def plot(self):
        # 辅助函数:安全获取坐标,不存在则返回默认值
        def get_coord(point, idx, default=0):
            return point[idx] if len(point) > idx else default
        
        xs = [get_coord(self.a1,0), get_coord(self.b1,0), get_coord(self.c1,0), get_coord(self.d1,0)]                           
        ys = [get_coord(self.a1,1), get_coord(self.b1,1), get_coord(self.c1,1), get_coord(self.d1,1)] 
        print(xs)
        print(ys)                           
        colors = ['c','m','b','y']

a1 = Points([1,2], [2], [3,4], [4,5])
a1.plot()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:20:16