Get all consecutive subbands of given length in python

I need a function that sets a range, it gives all the subranges (in a list or in a tuple) of the specified order. For instance:

my_function((0,1,2,3,4,5), 3)

should give:

[(0,1,2),(1,2,3),(2,3,4),(3,4,5)].

Is there such a function? Or is there something similar I can start with? (If he works on lists, he's fine too.)

+4
source share
2 answers

You can take all the relevant fragments of the list:

r = range(6)
n = 3
for i in range(len(r) - n + 1):
    print r[i: i + n]

Conclusion:

[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
+2
source

You can use zip:

>>> l=(0,1,2,3,4,5)
>>> zip(l,l[1:],l[2:])
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]

The following test shows that use zipis faster than isliceor just understanding the list:

:~$ python -m timeit "l=(0,1,2,3,4,5);from itertools import islice;[list(islice(l, i, i + 3)) for i in range(len(l) - 3 + 1)]"
100000 loops, best of 3: 4.47 usec per loop

:~$ python -m timeit "l=(0,1,2,3,4,5);[l[i: i + 3] for i in range(len(l) - 3 + 1)]"
1000000 loops, best of 3: 0.632 usec per loop

:~$ python -m timeit "l=(0,1,2,3,4,5);zip(l,l[1:],l[2:])"
1000000 loops, best of 3: 0.447 usec per loop

, , , izip islice itertools:

zip_longest(*(islice(l, i) for i in range(n))) # in python 3

izip(*(islice(l, i) for i in xrange(n))) # in python 2
+2

Source: https://habr.com/ru/post/1584772/


All Articles