Python 列表理解:如果另一个列表(具有相同长度)中的条件为真,则将元素添加到列表

Python List comprehension: Add Element to a list if condition in another list (with same length) is true

假设我有一个数组:

a =  [0.42, 0.18, 1.54, 2.9, 1.81, 2.35, 0.18, 1.54, 2.92]

具有以下(按元素)逻辑状态:

[False, True, False, False, False, False, True, False, False]

有没有一种很好的方法来使用列表推导式只将 True 元素添加到新列表中? 附加问题: 之后应弹出 a 中的真实元素(因为它们现在已经被处理)

你可以这样做:

>>> a =  [0.42, 0.18, 1.54, 2.9,  1.81, 2.35, 0.18, 1.54, 2.92]
>>> b = [False, True, False, False, False, False,  True, False, False]
>>> c = [num for num, truth_value in zip(a, b) if truth_value]
>>> c
[0.18, 0.18]

编辑: Q- c = [num for num, truth_value in zip(a, b) if truth_value] 这行是做什么的? A- 上面一行相当于下面的代码:

c = list()
for num, truth_value in zip(a, b):
    if truth_value:
        c.append(num)

Q-python中的zip()是什么? A-你可以看看here

如果还有人想了解更多解释,请通过评论告诉我。

只是为了提供一个替代方案,这也可以使用 itertools.compress(Python 3.1 或更高版本)来完成。 compress(a, b) 生成一个迭代器,它提供 a 的元素,其在 b 中的对应元素的计算结果为真。

例如:

>>> a =  [0.42, 0.18, 1.54, 2.9, 1.81, 2.35, 0.18, 1.54, 2.92]
>>> b = [False, True, False, False, False, False, True, False, False]
>>>
>>> c = list(itertools.compress(a, b))
>>> c
[0.18, 0.18]

仍然有必要从 a 中删除这些元素,使用列表理解或相同的技术,但翻转布尔值,这有点不那么优雅:

a = list(compress(a, (not x for x in b)))