0

2 つのパラメーター (リストと入力番号) を取る関数があります。入力リストをより小さなリストのグループに分割するコードがあります。次に、この新しいリストをチェックして、小さいリストのすべてが少なくとも入力番号と同じ長さであることを確認する必要があります。ただし、メインリスト内のサブリストを反復しようとすると、何らかの理由で特定のサブリストが除外されます (私の例では、メインリスト [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

リスト内包表記の「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]]
于 2013-08-30T14:32:15.083 に答える