2017-02-27 111 views
-1

我正在嘗試將一個嵌套列表拼合成一個列表並刪除所有Nones。但是當有多個無時,總是有一個無剩餘​​。也有時我有一個None作爲一個int類型(如在第一個列表李第二無)什麼?哈哈。請幫助我,並提前致謝。無法從列表中刪除NoneTypes(python)

#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() 
+0

_None爲int type_您可以將其輸出到列表 - 你是什麼意思? – DyZ

+2

不要嘗試從列表中刪除項目,同時迭代它。建立一個只包含你想要的項目的新列表要容易得多。 – roganjosh

+0

非常感謝roganjosh! –

回答

1

這裏是一個遞歸的發電機解決方案

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))