Reading sequence of values from list in python

  Kiến thức lập trình

I have list of values and a function that takes n>1 arguments. Values in list are in order (obviously) and I have to iterate through the list to check all possible sequences of values.

The code below works well, but doesn’t look really pythonic to me (I particularly don’t like “for i in range” construction). Is there any more elegant and possibly efficient way to achieve the same?

def foo(a,b,c): #function that takes 3 arguments
    print (a,b,c)

l=[1,2,3,4,5] #for this particular list (1,2,3), (2,3,4), (3,4,5) are triplets that should be analyzed by foo function
for i in range(len(l)-2):
    foo(*l[i:i+3])

Result:

1 2 3
2 3 4
3 4 5

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT