Reputation: 779
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]
Upvotes: 0
Views: 44
Reputation: 368944
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.
Upvotes: 3
Reputation: 16081
You can implement like using one line list comprehension.
[sum(A[i+1:B[B.index(i)+1]]) if i != B[-1] else sum(A[i+1:-1]) for i in B]
Result
[8, 7, 0]
If you don't want last slice sum use this.
[sum(A[i+1:B[B.index(i)+1]]) for i in B if i != B[-1]]
Result
[8, 7]
Upvotes: 1