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

Python列表扁平化时报错'int' object is not iterable 请求解决

问题解决:扁平化嵌套列表报错处理

报错原因

你的代码里,liste10包含整数和列表两种元素。当外层循环到第一个元素1时,内层for x in i试图遍历这个整数——但整数不是可迭代对象(无法用for循环遍历),因此抛出TypeError: 'int' object is not iterable。另外原代码里print(i)的逻辑也不对,就算没报错也无法输出正确的扁平化元素。

修复方案

基础版(仅处理一层嵌套)

遍历每个元素,判断类型:如果是列表就遍历其子元素添加到结果,否则直接添加元素本身:

liste10 = [1, [2,3], [4,5,6,7]]
flattened_list = []
for item in liste10:
    if isinstance(item, list):
        # 遍历子列表的元素并添加
        for sub_item in item:
            flattened_list.append(sub_item)
    else:
        # 直接添加非列表元素
        flattened_list.append(item)
print(flattened_list)  # 输出: [1, 2, 3, 4, 5, 6, 7]

递归版(支持多层嵌套)

如果你的列表可能有更深层次的嵌套(比如[1, [2, [3, 4]]]),可以用递归函数处理:

def flatten_nested_list(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            # 递归处理子列表,将结果扩展到当前列表
            result.extend(flatten_nested_list(item))
        else:
            result.append(item)
    return result

liste10 = [1, [2,3], [4,5,6,7]]
print(flatten_nested_list(liste10))  # 输出: [1, 2, 3, 4, 5, 6, 7]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:55:58