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

Python嵌套列表迭代报错:TypeError原因及正确遍历方法

问题原因与解决方法

错误原因

  1. 循环变量使用错误:你写的for i in unit1里,i是unit1中的每个子列表(比如["cats allowed", True]),不是整数索引。这时用unit1[i]相当于用列表当索引,自然会触发TypeError——列表索引只能是整数或切片。
  2. append方法使用错误:list.append()是原地修改列表,它的返回值是None。你把userPref.append(...)赋值给userPref,会导致userPref变成None,后续循环再调用append就会直接报错。

正确写法

方式一:修正原循环逻辑

unit1 = [["cats allowed", True], ["bedrooms", 0], ["Balcony", False]]

userPref = []
for item in unit1:
    # 直接取子列表的第二个元素
    current_value = item[1]
    userPref.append(current_value)
    print(current_value)

方式二:用列表推导式简化(更Pythonic)

如果只需要收集所有子列表的第二个元素,用列表推导式一行就能搞定:

unit1 = [["cats allowed", True], ["bedrooms", 0], ["Balcony", False]]

userPref = [item[1] for item in unit1]
# 遍历打印的话直接循环userPref就行
for value in userPref:
    print(value)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:27:19