2013-08-30 40 views
0

我有一個帶有兩個參數(列表和輸入數字)的函數。我有代碼將輸入列表分成更小的列表組。然後我需要檢查這個新列表並確保所有的小列表至少與輸入數字一樣長。然而,當我嘗試迭代主列表中的子列表時,出於某種原因某些子列表被排除在外(在我的示例中,它是位於mainlist [1]的子列表。任何想法爲什麼會發生這種情況?使用for循環迭代時,主列表中的Python子列表被跳過

def some_function(list, input_number) 
    ... 
    ### Here I have other code that further breaks down a given list into groupings of sublists 
    ### After all of this code is finished, it gives me my main_list 
    ... 

    print main_list 
    > [[12, 13], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]] 

    print "Main List 0: %s" % main_list[0] 
    > [12, 13] 

    print "Main List 1: %s" % main_list[1] 
    > [14, 15, 16, 17, 18, 19] 

    print "Main List 2: %s" % main_list[2] 
    > [25, 26, 27, 28, 29, 30, 31] 

    print "Main List 3: %s" % main_list[3] 
    > [39, 40, 41, 42, 43, 44, 45] 

    for sublist in main_list: 
     print "sublist: %s, Length sublist: %s, input number: %s" % (sublist, len(sublist), input_number) 
     print "index of sublist: %s" % main_list.index(sublist) 
     print "The length of the sublist is less than the input number: %s" % (len(sublist) < input_number) 
     if len(sublist) < input_number: 
      main_list.remove(sublist) 
    print "Final List >>>>" 
    print main_list 

> sublist: [12, 13], Length sublist: 2, input number: 7 
> index of sublist: 0 
> The length of the sublist is less than the input number: True 

> sublist: [25, 26, 27, 28, 29, 30, 31], Length sublist: 7, input number: 7 
> index of sublist: 1 
> The length of the sublist is less than the input number: False 

> sublist: [39, 40, 41, 42, 43, 44, 45], Length sublist: 7, input number: 7 
> index of sublist: 2 
> The length of the sublist is less than the input number: False 

> Final List >>>> 
> [[14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]] 

爲什麼我的子列表位於主列表[1]被完全忽略?感謝您提前提供任何幫助。

回答

0

看起來您在迭代時正在更改列表。導致未定義的行爲。

查看this answer

+0

啊我明白了。它非常有意義,雖然直到你指出它並不明顯。 – GetItDone

1

列表理解中的'if'將起作用:

>>> x = [[12, 13], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]] 
>>> [y for y in x if len(y)>=7] 
[[25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]] 
+0

感謝您的示例。它乾淨而簡單。 – GetItDone

+0

+1爲一個乾淨的替代品 –