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

为何使用列表索引赋值时会出现'int object does not support item assignment'错误

问题:int object does not support item assignment 错误原因分析

原研究代码

"""Processes an encoded symbol together with its coefficients."""
def consume_packet(self, coefficients, packet):    
    if not self.is_fully_decoded():
        # add new symbol to decoder matrix and packet vector
        self.coefficient_matrix[self.num_independent][0:self.num_symbols] = coefficients
        self.packet_vector[self.num_independent] = packet

测试代码及错误

测试代码:

packet = [1, 2, 4]
num_symbols = 3
coefficient_matrix = [1, 2, 4, 5, 6, 7]
coefficient_matrix[0][0:num_symbols] = packet # I think this is supposed to extract the packet
print(coefficient_matrix[0])
print(coefficient_matrix[0][0:num_symbols])

执行后报错:int object does not support item assignment

错误原因

你定义的coefficient_matrix是一维整数列表,里面每个元素都是整数类型。执行coefficient_matrix[0]时,得到的是整数1,而整数属于不可变类型,不支持[0:num_symbols]这类切片赋值操作。

原代码中的self.coefficient_matrix是二维矩阵(二维列表),即每个元素本身是一个列表(对应矩阵的一行)。比如正确的矩阵定义应该是[[0,0,0], [0,0,0]]这类结构,此时coefficient_matrix[0]取到的是一个列表,才能进行切片赋值。

修正后的测试代码示例

packet = [1, 2, 4]
num_symbols = 3
# 定义两行三列的二维矩阵,初始值设为0
coefficient_matrix = [[0,0,0], [0,0,0]]
coefficient_matrix[0][0:num_symbols] = packet
print(coefficient_matrix[0])  # 输出: [1, 2, 4]
print(coefficient_matrix[0][0:num_symbols])  # 输出: [1, 2, 4]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:30:30