无法从列表中删除 NoneTypes (python)

not able to remove NoneTypes from list (python)

我正在尝试将嵌套列表展平为一个列表并删除所有 None。但是,当有多个 None 时,总会剩下一个 None。有时我也有一个 None 作为 int 类型..(与第一个列表 li 中的第二个 None 一样)到底是什么?哈哈。请帮助我并提前致谢。

#test lists--li is the orignal one provided by Button
li = [0, 2, [[2, 3], 8, 100, None, [[None]]], -2]
li1 = [-100, -100, [[[None,None]]]]
li2 = [[[[[None,None,1,2,3]]]], 6, 0, 0, 0]
li3 = [None, [None], 56, 78, None]
li4 = [[[[[None,1,2,3]]]], 6, 0, 0, 0]

#solution is theta(n) or more specifically O(n)
#which is the best case solution since we must
#loop the entire list

def flatten(li):
    i = 0
    while i < len(li):

        #only execute if the element is a list
        while isinstance(li[i], list):

        #taking the element at index i and sets it as the
        #i'th part of the list. so if l[i] contains a list
        #it is then unrolled or 'unlisted'

        li[i:i + 1] = li[i]

        i += 1

    #for li: for some reason the 2nd None at
    #index 7 is an int, probably because there
    #might've been an int at that index before manipulation?

    #for li1: the 2nd None or element at index 3
    #is of class 'NoneType' but the removal is not
    #occuring.. 

    for element in li:
        if element is None:
            li.remove(element)


    #conclusion: there is always one None remaining if
    #there is more than one None to begin with..
    return li

def main():
    flatten(li)
    print(li)
    flatten(li1)
    print(li1)
    flatten(li2)
    print(li2)
    flatten(li3)
    print(li3)
    flatten(li4)
    print(li4)

if __name__ == '__main__':
   main()

这是一个递归生成器解决方案

def flatten(l):
   for i in l:
       if i is None:
           continue
       elif isinstance(i, list):
           for ii in flatten(i):
               yield ii
       else:
           yield i

如果你想要一个列表,你可以将它的输出转换成列表list(flatten(li))