2

I have a list of length L, with some random values:

list1 = [3, 1, 1, 6, 8, 3, 7, 4, 8, 4]

and another list of the same length, with boolean values

list2 = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]

I want to sum the values of list1 where the corresponding element of list2 is 1. (in this case 6+8+3)

is there an easy way to make it in Python?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • What have you done? Did you make any attempts to solve the problem?. Also possible Duplicate of [How can I add the corresponding elements of several lists of numbers?](http://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers) – cyberbemon Sep 02 '14 at 15:58

3 Answers3

4

You can use itertools.compress with sum:

>>> import itertools
>>> list1 = [3, 1, 1, 6, 8, 3, 7, 4, 8, 4]
>>> list2 = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]
>>> list(itertools.compress(list1, list2))
[6, 8, 3]
>>> sum(itertools.compress(list1, list2))
17
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

Yes, using sum and itertools.compress:

>>> from itertools import compress
>>> sum(compress(list1, list2))
17

Explanation: compress() takes two iterables, and yields elements from the first if the corresponding element of the second is truthy. sum() ... well, you can probably guess.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
0

You can also do a conditional comprehension with zip:

>>> list1 = [3, 1, 1, 6, 8, 3, 7, 4, 8, 4]
>>> list2 = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]

>>> sum(item for item, flag in zip(list1, list2) if flag)  
17

The if flag checks if the corresponding item is not-zero. If you want an explicit check for 1:

>>> sum(item for item, flag in zip(list1, list2) if flag == 1)  
17
MSeifert
  • 145,886
  • 38
  • 333
  • 352