2013-08-30 41 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为一个干净的替代品 –