只有在单独的布尔列表中的元素为True时,才会在Python列表中求和元素 [英] Sum elements in python list only if elements in a separate boolean list are True

查看:714
本文介绍了只有在单独的布尔列表中的元素为True时,才会在Python列表中求和元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个python列表,

I have two python lists,

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

列表A和B的长度相同。

lists A and B are the same length.

我想只统计A中对应于B中True元素的元素。
我知道我可以这样做:

I want to sum only the elements in A that correspond to True elements in B. I know I can do that with something like:

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

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

but I was wondering if there was a more elegant solution that didn't involve looping over elements in each list?

推荐答案

使用 itertools.compress

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

执行 itertools.compress 在链接页上描述。非常简单,因此您不必导入 itertools 1

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 在C中实现,因此应该更快

1 OTOH, itertools.compress is implemented in C, and therefore should be faster

这篇关于只有在单独的布尔列表中的元素为True时,才会在Python列表中求和元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆