KevinOelen KevinOelen - 5 months ago 5
Python Question

Iterating list with given index list in python

I have a list

A = [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1]
and
B = [0, 7, 11]
. List
B
shows the index of negative integer number index.

How can I return the sum of each slice of the list: For example sum of
A[0+1:7]
and
A[7+1:11]

Answer

Using zip, you can convert [0, 7, 11] to the desired slice index pairs (1:7 / 8:11):

>>> zip(B, B[1:])  # In Python 3.x, this will return an iterator.
[(0, 7), (7, 11)]
>>> [(i+1, j) for i, j in zip(B, B[1:])]
[(1, 7), (8, 11)]

>>> [A[i+1:j] for i, j in zip(B, B[1:])]
[[2, 1, 2, 0, 2, 1], [4, 3, 0]]
>>> [sum(A[i+1:j]) for i, j in zip(B, B[1:])]
[8, 7]

UPDATE

Another way to accomplish what you want without defining B using itertools.groupby:

>>> A = [-8, 3, 0, 5, -3, 12]
>>> import itertools
>>> [sum(grp) for positive, grp in itertools.groupby(A, lambda x: x >= 0) if positive]
[8, 12]

key function was used to split 0 and positive numbers and negative numbers.