我们有一个函数,它接收两个参数(一个列表和一个输入数字)。我们有代码将输入列表分解为更小的分组列表。然后我们需要检查这个新列表并确保所有较小的列表都至少与输入数字一样长。然而,当我们尝试遍历主列表中的子列表时,由于某种原因,某些子列表被排除在外(在我的示例中,位于 mainlist[1] 的子列表被排除在外)。你知道为什么发生这种情况吗?
以下是一些示例代码:
def some_function(list, input_number):
...
### 这里有其他代码可以进一步将给定列表分解为子列表的分组
### 在所有这些代码完成后,它会为我们提供 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] 的子列表被完全跳过?提前感谢任何帮助。
## 解决方案
问题的原因是,在 for 循环中删除子列表时,列表的长度会发生变化。这导致列表的索引发生变化,并且子列表可能会被跳过。为了解决这个问题,我们可以使用列表推导来创建一个新的列表,其中包含满足条件的子列表。
以下是可以解决该问题的代码示例:
```python
def some_function(list, input_number):
...
### 这里有其他代码可以进一步将给定列表分解为子列表的分组
### 在所有这些代码完成后,它会为我们提供 main_list
...
main_list = [sublist for sublist in main_list if len(sublist) >= input_number]
print main_list
在这个示例中,我们使用列表推导来创建新的 main_list。列表推导会遍历 main_list 中的每个子列表,并检查它的长度是否大于或等于 input_number。如果满足条件,则子列表将被添加到新的 main_list 中。
这样,我们就确保了只有满足条件的子列表才会被保留在 main_list 中,并且在使用 for 循环遍历时,不会跳过任何子列表。