isinstance(对象,类型)给了我一个错误 - 此外,扁平化嵌套列表



我是一个初学者程序员,我试图解决一个prolog问题,即扁平化嵌套列表。我的尝试:

a = [1, 2, 3, [1, 2, 3], 4, 5]
def flatten(list):
    new = []
    for i in list:
        new.append(','.join(int(i)) for i in list)
    for ele in list:
        if isinstance(ele, list):
            flatten(ele)
            return new
        else:
            pass
        return new
flatten(a)

我收到一个错误,说:

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types. 

以为我正确地实现了它,因为我传递了 ele(对象)和列表(类型)?它在解释器中起作用,但在这里不起作用。

还有关于尝试扁平嵌套列表的代码的任何建议?

通过执行def flatten(list),您使用list作为函数参数的名称,这会阻止访问名为 list 的内置类型。 为变量使用不同的名称。

至于如何扁平化嵌套列表,谷歌搜索这个问题会给你几十个甚至数百个答案。

您在flatten(list)函数中将list定义为变量。

请避免使用数据类型的变量名。请将其更改为flatten(my_list)它将起作用。

你的代码中存在一些缺陷:

1 never use list as variable name
2 new.append(','.join(int(i)) for i in list)  
   `join` wont take int type, will raise TypeError
    it should be new.append(','.join(str(i)))
3 you are using `return` once it returned , it come out of the function

相关内容

最新更新