KevinOelen - 1 year ago 40

Python Question

I have a list

`A = [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1]`

`B = [0, 7, 11]`

`B`

How can I return the sum of each slice of the list: For example sum of

`A[0+1:7]`

`A[7+1:11]`

Answer Source

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.