0

我有一个带有两个参数(一个列表和一个输入数字)的函数。我有将输入列表分成更小的列表分组的代码。然后我需要检查这个新列表并确保所有较小的列表至少与输入数字一样长。但是,当我尝试遍历主列表中的子列表时,由于某种原因,某些子列表被排除在外(在我的示例中,它是位于 mainlist[1] 的子列表。知道为什么会这样吗?

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

为什么我的位于 mainlist[1] 的子列表被完全跳过???感谢您提前提供任何帮助。

4

2 回答 2

1

列表理解中的“如果”将起作用:

>>> 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]]
于 2013-08-30T14:32:15.083 回答
0

看起来您在迭代列表时正在更改列表。这是不允许的,并且可能导致未定义的行为。

看到这个答案

于 2013-08-30T14:17:38.320 回答