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