List Python基于条件true映射两个列表
我有两份清单:List Python基于条件true映射两个列表,list,python-2.7,List,Python 2.7,我有两份清单: A: [ True True True False True False True ] B: ['A', 'B', 'C', 'D', 'E', 'F', 'G'] 我只想从列表B中获取那些值,其中列表A为True 期望输出: ['A', 'B', 'C', 'E', 'G'] 将相当简单的问题作为问题发布;这是解决办法。如果您能在询问之前试一试,我将不胜感激 代码: a = [True, True, True, False, True, False, True] b
A: [ True True True False True False True ]
B: ['A', 'B', 'C', 'D', 'E', 'F', 'G']
我只想从列表B
中获取那些值,其中列表A
为True
期望输出:
['A', 'B', 'C', 'E', 'G']
将相当简单的问题作为问题发布;这是解决办法。如果您能在询问之前试一试,我将不胜感激 代码:
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']
将相当简单的问题作为问题发布;这是解决办法。如果您能在询问之前试一试,我将不胜感激 代码:
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']
我希望这也适用于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
我希望这也适用于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
您可以使用:
您可以使用:
如果您不想导入
itertools
,那么使用内置函数进行简单的列表理解就足够了
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']
如果您不想导入
itertools
,那么使用内置函数进行简单的列表理解就足够了
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']