Python嵌套列表迭代报错:TypeError原因及正确遍历方法
问题原因与解决方法
错误原因
- 循环变量使用错误:你写的
for i in unit1里,i是unit1中的每个子列表(比如["cats allowed", True]),不是整数索引。这时用unit1[i]相当于用列表当索引,自然会触发TypeError——列表索引只能是整数或切片。 - 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
相关产品推荐
相关产品推荐

