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

Python通过列表索引创建新列表时遇TypeError问题求助

问题修复:列表访问与初始化错误

错误原因

  1. 列表元素访问语法错误:你用my_family(removed_index)获取列表元素是错误的。Python中访问列表元素必须用方括号[],圆括号()是用来调用函数/可调用对象的,列表本身不是可调用对象,因此触发TypeError: 'list' object is not callable。
  2. 列表未初始化就调用append:使用removed_family.append()前,必须先创建空列表removed_family = [],否则会报变量未定义的错误。

正确代码示例

方式1:直接通过索引创建新列表

my_family = ['Chuck', 'Donna', 'Tammy', 'Barb', 'Sean', 'Chance', 'Gabe']

removed_person = input('Type the name of the person to remove from your family')

removed_index = my_family.index(removed_person)

print(removed_person)
print(removed_index)

# 修正:用方括号访问列表元素
removed_family = [my_family[removed_index]]

print(removed_family)

方式2:初始化空列表后追加元素

my_family = ['Chuck', 'Donna', 'Tammy', 'Barb', 'Sean', 'Chance', 'Gabe']

removed_person = input('Type the name of the person to remove from your family')

removed_index = my_family.index(removed_person)

print(removed_person)
print(removed_index)

# 先初始化空列表,再追加元素
removed_family = []
removed_family.append(my_family[removed_index])

print(removed_family)

额外提示

如果用户输入的姓名不在my_family列表中,index()方法会抛出ValueError。如果需要避免崩溃,可以添加异常处理:

try:
    removed_index = my_family.index(removed_person)
except ValueError:
    print(f"{removed_person} is not in the family list.")
    # 可添加后续逻辑处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:40:24