简体   繁体   English

isinstance(object,type)给我一个错误-另外,展平嵌套列表

[英]isinstance(object, type) is giving me an error - Also, flattening a nested list

I am a beginner programmer, and I attempted to solve one of the prolog questions which was to flatten a nested list. 我是一名初学者程序员,我试图解决一个序言问题,该问题是将嵌套列表展平。 My attempt: 我的尝试:

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)

I get an error saying: 我收到一条错误消息:

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

I thought I implemented it correctly since I passed on ele (the object) and list (type)? 我以为自从传递ele(对象)和list(类型)以来,我就正确实现了? It worked in the interpreter, but not here. 它在解释器中有效,但在这里不起作用。

Also any advice for the code in terms of trying to flatten a nested list? 在尝试展平嵌套列表方面,对代码还有任何建议吗?

By doing def flatten(list) , you used list as the name of your function parameter, which blocks access to the builtin type named list . 通过执行def flatten(list) ,您可以将list用作函数参数的名称,该参数将阻止对名为list的内置类型的访问。 Use a different name for your variable. 为变量使用其他名称。

As for how to flatten nested lists, googling that question will give you dozens if not hundreds of answers. 至于如何展平嵌套列表,搜索该问题将为您提供数十个甚至数百个答案。

You are defining list as variable in your flatten(list) function. 您将在flatten(list)函数中将list定义为变量。

Please avoid to use variable name of data type. 请避免使用数据类型的变量名。 Please change it to flatten(my_list) it will work. 请更改为flatten(my_list) ,它将起作用。

there are some flaw in your code: 您的代码中存在一些缺陷:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM