Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform multiple list slices at the same time?

Tags:

python

slice

Say I have a list:

L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

and I have a list of indices:

indices = (2, 5, 7)

What I would like to be able to do is slice the list at all 3 indices at the same time. In other words, id like to perform the following lines of code in one line:

sub1 = L1[:2]
sub2 = L1[2:5]
sub3 = L1[5:7]
sub4 = L1[7:]

I could fairly easily write a function that does this, but I was wondering if it is possible to do this in one expression.

like image 271
Malonge Avatar asked Dec 15 '22 10:12

Malonge


2 Answers

You could use operator.itemgetter with slice objects:

>>> from operator import itemgetter
>>> get = itemgetter(slice(0, 2), slice(2, 5), slice(5, 7), slice(7, None))

>>> values = range(1, 10)
>>> values
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> get(values)
([1, 2], [3, 4, 5], [6, 7], [8, 9])
like image 112
Peter Wood Avatar answered Dec 17 '22 01:12

Peter Wood


Are you looking for a one liner? We could give you one, but I would just keep it simple:

L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
indices = (2, 5, 7)

start = 0
sections = []
for end in indices:
    sections.append(L1[start:end])
    start = end
sections.append(L1[start:])

for part in sections:
    print part
# [1, 2]
# [3, 4, 5]
# [6, 7]
# [8, 9]
like image 27
Bi Rico Avatar answered Dec 16 '22 23:12

Bi Rico