HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Get array slices from list of lengths

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
slicesarraygetlengthslistfrom

Problem

I have a list of segment lengths and I want to convert it into array slices:

segment_lens = [2, 5, 5]

last_end = 0
start = 0
end = 0

for s_i in range(len(segment_lens)):
    start = last_end
    end += segment_lens[s_i]
    print("Slice: [%s,%s]" %(start, end,))
    last_end = end


Here is the intended output, which in my application I would use to slice a list:

Slice: [0,2]
Slice: [2,7]
Slice: [7,12]


Is there a better way to do this? I feel like there should be a python built-in for this, but I'm not sure.

Solution

I would probably use iter for this:

def get_chunks(l, chunk_lengths):
    it = iter(l)
    for chunk_length in chunk_lengths:
        yield [next(it) for _ in range(chunk_length)]


Usage:

>>> get_chunks(range(100), [1,2,5])

>>> list(get_chunks(range(100), [1,2,5]))
[[0], [1, 2], [3, 4, 5, 6, 7]]


Review:

I would make your code at least a function that yeilds the slices and give it a nice name, like I did in the function above.

Note that it is frowned upon in python to iterate over the indices of a list, if all you need are the elements. So prefer this:

for item in l:
    print(item)


over

for i in range(len(l)):
    print(l[i])


Also note that using "%s" % var style formatting is the old way of doing it. It is recommended to use str.format, which offers a lot more possibilities (none of which you need here, though).

print("Slice: [{},{}]".format(start, end,))

Code Snippets

def get_chunks(l, chunk_lengths):
    it = iter(l)
    for chunk_length in chunk_lengths:
        yield [next(it) for _ in range(chunk_length)]
>>> get_chunks(range(100), [1,2,5])
<generator object get_chunks at 0x7f2744f68910>

>>> list(get_chunks(range(100), [1,2,5]))
[[0], [1, 2], [3, 4, 5, 6, 7]]
for item in l:
    print(item)
for i in range(len(l)):
    print(l[i])
print("Slice: [{},{}]".format(start, end,))

Context

StackExchange Code Review Q#150378, answer score: 4

Revisions (0)

No revisions yet.