0

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]

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer. It works but in case A = [-8, 3, 0, 5, -3, 12] and B = [0,4] it doesn't return 12?
@KevinOelen, A[0+1:4] == [3, 0, 5].
@KevinOelen, If you want to get [12], you need to specify B = [4, 6] or B = [0, 4, 6].
@KevinOelen, Run this before running the code in the answer to handle such case: if B[-1] < len(A): B.append(len(A))
@KevinOelen, I updated the answer to include other version that does not require you to define B (indices of negative numbers) yourself.
1

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]

3 Comments

Thanks for the answer. Can you see above comment and answer for that?
It should return 12 since there is a positive integer after -3
A[0+1:4] = [3, 0, 5] ? Right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.