Advertisements
This is my list:
lst = [1,2,3,4,5]
If I do this:
from itertools import permutations
lst = [1,2,3,4,5]
l = []
lperm = permutations(lst,3)
for i in lperm:
l.append(i)
print(l)
It returns this:
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 2), ...]
But this is what I want:
[(1, 2, 3),(2, 3, 4),(3, 4, 5)]
Anyone has an answer for this?
>Solution :
l = 3
lst = [1, 2, 3, 4, 5]
print([lst[x:x+l] for x in range(len(lst)-l+1)])
or if you need those tuples:
print([tuple(lst[x:x+l]) for x in range(len(lst)-l+1)])
If you don’t want to hold all the values in the memory:
l = 3
lst = [1, 2, 3, 4, 5]
def slider(iterable, l):
for x in range(len(iterable)-l+1):
yield tuple(lst[x:x+l])
for i in slider(lst, l):
print(i)