python - 嵌套循环。如何仅遍历列表中的左、中和右元素?
问题描述
有两个数字列表。
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
解决方案
你只需要适当地切片它:
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]
推荐阅读
- php - 如何加载与 Eloquent 的关系?
- amazon-web-services - 如何下载 FederationMetadata xml 文件
- c - 为什么指针 (*) 和数组 ([]) 符号绑定到变量名而不是键入变量声明?
- database - Mongoimport忽略csv中的前导零
- maximo - 如何在 maximo 中隐藏具有类似于银行帐号的特殊字符的字段值
- excel - 根据 Active Cell.Offset 变量删除形状(旋转按钮)
- git - `[--]` 中的 git diff 是什么意思
- python - 如何修复 TypeError:“系列”对象是可变的,因此它们不能被散列
- c - 如何在c中填充数组?(赋值从没有强制转换的指针生成整数)
- forms - 函数 createInnerHTML - 如何与其他表单输入重复?