I've been through itertools inside and out and I cannot figure out how to do the following. I want to take a list.
x = [1,2,3,4,5,6,7,8]
and I want to get a new list:
y = [[1],[1,2],[1,2,3],.......[2],[2,3],[2,3,4].....[8]]
I need a list of all slices, but not combinations or permutations.
x = list(zip(x[::2], x[1::2]))
is close, but doesn't do exactly what I'm hoping
You can generate a slice object using the built-in function slice() . If you want to repeatedly select the items at the same position, you only need to generate the slice object once. slice(start, stop, step) is equivalent to start:stop:step . If two arguments are specified, step is set to None .
As shown in the above syntax, to slice a Python list, you have to append square brackets in front of the list name. Inside square brackets you have to specify the index of the item where you want to start slicing your list and the index + 1 for the item where you want to end slicing.
With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.
The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.
Use combinations
not of x
, but of the range
of possible slice indices (including one past the end, thus len(x)+1
, since slices are exclusive on the end) to make the slice end points, then use them to slice x
:
from itertools import combinations
y = [x[s:e] for s, e in combinations(range(len(x)+1), 2)]
That gets exactly what you're going for as straightforwardly as possible. If you want (possibly) faster map
based code, you can rephrase it as (list
wrapper unnecessary on Python 2):
from itertools import combinations, starmap
y = list(map(x.__getitem__, starmap(slice, combinations(range(len(x)+1), 2))))
which gets the same result, but without any Python bytecode execution per-item, which might run faster (implementation dependent).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With