python - 列表对中的一个元素与其他元素
问题描述
从列表中获取一个元素并根据条件将其与所有下一个元素一起打印。
l = [0,1,2,3]
count = 0
def ab():
for index, elem in enumerate(l):
global count
if (index+1 <= len(l) and count+1 < len(l)):
print('finding from', str(l[count]) ,'to',l[index])
if index == len(l)-1:
count += 1
print('pass',count)
ab()
ab()
上述函数的输出
pass 0
finding from 0 to 0
finding from 0 to 1 # expect pass 0 to start from here
finding from 0 to 2
finding from 0 to 3
pass 1
finding from 1 to 0
finding from 1 to 1
finding from 1 to 2 # expect to start from here
finding from 1 to 3
pass 2
finding from 2 to 0
finding from 2 to 1
finding from 2 to 2
finding from 2 to 3 # expect to start from here
我所期望的 - 从列表中获取元素并与它之后的值配对而不是之前
pass 0
finding from 0 to 1
finding from 0 to 2
finding from 0 to 3
pass 1
finding from 1 to 2
finding from 1 to 3
pass 2
finding from 2 to 3
解决方案
你让这变得比它需要的更复杂。你只需要一个循环中的循环,如下所示:
L = [0,1,2]
for i in range(len(L)):
print(f'pass {i}')
for j in range(i, len(L)):
print(f'finding from {i} to {j+1}')
推荐阅读
- python - How to tackle calculating then verifying 10^8 solutions to find the one true answer?
- android - 如何在构建时忽略一个类 Gradle
- spring - 如何使用 SpringIntegration 将文件转换为字符串
- spring - spring 如何从资源映射中访问特定的一个文件
- python - 使用数组作为多维数组的索引掩码
- python - 如何在python中的正则表达式中获取组
- node.js - 如何在 aws 中为 node.js 运行 cron 作业
- ios - 在uitableview swift4中展开和折叠多级部分
- swift - 在 appdelegate 中添加一个 UITabbarController
- angular - 如何以角度将对象从服务返回到组件