2016-04-08 80 views
2

我有两个蟒列表,萨姆元件仅当在一个单独的布尔列表元素为True

A = [ 1, 2, 3, 4, 5 ] 
B = [ True, False, False, True, True ] 

列表A和B是相同的长度。

我要总结仅在对应于B. 真正的元素,我知道我能做到这一点的东西,如元素:

sum([A[x] for x in xrange(len(A)) if B[x]]) 

,但我不知道是否有一个更优雅的解决方案那不涉及循环每个列表中的元素?

+1

如果' A'和'B'在哪里'numpy.array's。所有你必须做的:'A [B] .sum()'。 – Akavall

回答

2

发电机表达+ sum

>>> A = [1, 2, 3, 4, 5] 
>>> B = [True, False, False, True, True] 
>>> sum(a for a,b in zip(A, B) if b) 
10 
1

代码

A = [ 1, 2, 3, 4, 5 ] 
B = [ True, False, False, True, True ] 

sum_ = sum([numa for (numa, numb) in zip(A, B) if numb]) 
print(sum_) 

10 

工作原理:

如果我们将列表理解扩大一点,我们可以更清楚地看到发生了什么。

nums_to_sum = [] 
for numa, numb in zip(A, B): 
    if numb: 
     nums_to_sum.append(numa) 
sum_ = sum(nums_to_sum) 
6

使用itertools.compress

>>> from itertools import compress 
>>> sum(compress(A, B)) 
10 

itertools.compress实行的是链接的页面描述。这是短期和简单,让你不已经进口itertools

>>> sum(a for a, b in zip(A, B) if b) 
10 

OTOH,itertools.compress是用C实现的,因此,应该快了