我有两个 python 列表,
A = [ 1, 2, 3, 4, 5 ]
B = [ True, False, False, True, True ]
列表 A 和 B 的长度相同。
我只想对 A 中与 B 中的 True 元素相对应的元素求和。
我知道我可以用以下方法做到这一点:
sum([A[x] for x in xrange(len(A)) if B[x]])
但我想知道是否有一个更优雅的解决方案,不涉及循环每个列表中的元素?
Using itertools.compress https://docs.python.org/3/library/itertools.html#itertools.compress:
>>> from itertools import compress
>>> sum(compress(A, B))
10
The implementation of itertools.compress
is described on the linked page. It's short and simple, so you don't have to import itertools
1:
>>> sum(a for a, b in zip(A, B) if b)
10
1 OTOH, itertools.compress
is implemented in C, and therefore should be faster
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)