Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting every slice of a list

Tags:

python

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

like image 407
T.J. Avatar asked Oct 25 '17 20:10

T.J.


People also ask

How do you slice every element in a list Python?

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 .

Can you slice a list of lists in Python?

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.

How will you slice a list?

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.

Is slicing possible in list?

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.


1 Answers

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).

like image 52
ShadowRanger Avatar answered Oct 24 '22 10:10

ShadowRanger