首页 > 解决方案 > 列表对中的一个元素与其他元素

问题描述

从列表中获取一个元素并根据条件将其与所有下一个元素一起打印。

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  

标签: python

解决方案


你让这变得比它需要的更复杂。你只需要一个循环中的循环,如下所示:

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}')

推荐阅读