Python deletes duplicate elements in multi-level lists and expands multi-level list elements

I wrote a function directly here, using recursion, and then deleting duplicate elements, not much to say about the code:

a = ["abc",["abc",1,[123,"abc"]],123]

def shanchu(list1):
    #这个函数的功能是删除多层列表中的重复元素
    result = []
    for i in list1:
        if isinstance(i,list):
            shanchu(i)
        else:
            if i not in result:
                result.append(i)
    return result

print(shanchu(a))

Then paste a running effect diagram:
insert image description here
expand the multi-layer list element function and output:

a = ["abc",["abc",1,[123,"abc"]],123]

def zhankai(list1):
    if isinstance(list1,list):
        for i in list1:
            for element in zhankai(i):
                yield element
    else:
        yield list1
print(list(zhankai(a)))

Expand the result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43635067/article/details/128915379