【问题标题】:Python sublist within a main list being skipped when iterating using a for loop [duplicate]使用for循环进行迭代时跳过主列表中的Python子列表[重复]
【发布时间】:2013-08-30 14:08:58
【问题描述】:

我有一个带有两个参数(一个列表和一个输入数字)的函数。我有将输入列表分成更小的列表分组的代码。然后我需要检查这个新列表并确保所有较小的列表至少与输入数字一样长。但是,当我尝试遍历主列表中的子列表时,由于某种原因,某些子列表被排除在外(在我的示例中,它是位于 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] 的子列表被完全跳过???提前感谢您的帮助。

【问题讨论】:

    标签: python python-2.7 for-loop iteration


    【解决方案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]]
    

    【讨论】:

    • 感谢您的示例。它干净简单。
    • +1 一个干净的替代品
    【解决方案2】:

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

    this answer

    【讨论】:

    • 啊,我明白了。这是完全有道理的,虽然在你指出之前并不是很明显。
    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2021-08-23
    • 2016-09-04
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多