Python映射基于条件true的两个列表

时间:2016-04-15 12:47:56

标签: list python-2.7

我有两个清单:

A: [ True  True  True False  True False  True ]
B: ['A', 'B', 'C', 'D', 'E', 'F', 'G']

我想只获取列表B中列出ATrue的那些值。

期望的输出:

['A', 'B', 'C', 'E', 'G']

4 个答案:

答案 0 :(得分:2)

您可以使用itertools.compress(...)

import itertools
a = [ True, True, True, False, True, False, True ]
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

ab = itertools.compress(b, a)
print(list(ba))

答案 1 :(得分:1)

如果您不想导入itertools,使用zip内置函数的简单列表理解就足够了。

conditions =  [True, True, True, False, True, False, True]
objects = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
result = [o for o, c in zip(objects, conditions) if c]
assert result == ['A', 'B', 'C', 'E', 'G']

答案 2 :(得分:0)

作为问题发布的相当简单的问题;这是解决方案。如果你能在这里问之前尝试一下,我将不胜感激。

代码:

a = [True, True, True, False, True, False, True]
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
res = []
for x in range(len(a)):
    if a[x]==True:
        res.append(b[x])
print res

输出:

['A', 'B', 'C', 'E', 'G']

答案 3 :(得分:0)

我希望这也适用于python 2;我在这台电脑上只有3台,但仍然是:

a = [ True, True, True, False, True, False, True ]
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
ab = []

for i, j in enumerate(a):
    if j == True:
        ab.append(b[i])
# in python 3 this was print(ab) :) I ported :)
print ab
相关问题