首页 > 解决方案 > 嵌套循环。如何仅遍历列表中的左、中和右元素?

问题描述

有两个数字列表。

list_1 = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]
list_2 = [0, 2, 5, 7, 8]

for i in range(len(list_1)):
    for l in list_2:
        ...

因此,循环每次都会遍历 list_2 中的所有 l

我只需要在每次迭代中使用 i 迭代左、中和右元素。

For i = 0 there will be elements l = [0, 2, 5]
For i = 1 there will be elements l = [2, 5, 7]
For i = 2 there will be elements l = [5, 7, 8]
For i = 3 there will be elements l = [7, 8]
For i = 4 there will be elements l = [8]
For i = 5 there will be elements l = [8]
For i = 6 there will be elements l = [8]
etc

标签: pythonpython-3.xlist

解决方案


你只需要适当地切片它:

list_1 = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]
list_2 = [0, 2, 5, 7, 8]
l = len(list_2)

for i, _ in enumerate(list_1):
    for j in lst2[min(i, l-1):i+3]:
        ...

切片产生以下结果:

[0, 2, 5]
[2, 5, 7]
[5, 7, 8]
[7, 8]
[8]
[8]
[8]
[8]
[8]
[8]
[8]

推荐阅读