2017-02-27 5 views
-1

入れ子リストを1つのリストにまとめて、すべてのNonesを削除しようとしています。しかし、1つ以上のNoneがある場合、常に1つのNoneが残ります。また時々私はint型としてNoneを持っています..(最初のリストliの2番目のNoneと同じように)何ですか?ハハ。私を助けて、事前に感謝してください。ここでリストから型を削除できません(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をしたい場合はリストし、その出力を変換することができます - あなたはこれで何を意味するのですか? – 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 

であるあなたはint型のTYPE_としてリストlist(flatten(li))

関連する問題