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

遍历列表创建新列表时append函数触发AttributeError错误

问题分析与解决

错误根源

list.append()是原地修改列表的方法,它本身没有返回值(返回None)。你在代码里把append的结果重新赋值给了new_feedback:

new_feedback =  new_feedback.append(str(word))

第一次执行这行代码后,new_feedback就被覆盖成了None。第二次循环时,调用None.append()自然会触发AttributeError: 'NoneType' object has no attribute 'append'。

修复方案

1. 正确初始化空列表

先确保new_feedback初始化为空列表:

new_feedback = []

2. 移除多余的赋值操作

直接调用append,不要把返回值赋给原变量:

for word in feedback_list:
    if word not in rejected_words:
        new_feedback.append(str(word))  # 这里不需要赋值
        print(new_feedback)
    # else分支按需保留

额外优化写法

如果只是做列表过滤,还可以用更简洁的列表推导式替代循环,从根源避免这类赋值错误:

new_feedback = [str(word) for word in feedback_list if word not in rejected_words]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:47:05