Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a combination with ascending numbers in Python 3?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading