返回true情况下,我有值的列表:映射布尔值的数组值的数组,在Python
a = [1,2,3,4]
和布尔值的对应列表:
b = [True, True, False, True]
我想将b映射到一个这样的位置,使得我得到所有值,使得它们在b中的对应值为'真'。因此,在这种情况下,答案是[1,2,4]
我能想到的唯一方法是循环遍历b的元素,获取索引为True,然后检索相应的索引一个。所以像这样:
def maplist(l1, l2):
# list1 is a list of Booleans to map onto list2
l2_true = []
for el in range(len(l1)):
if l1[el] == True:
l2_true.append(l2[el])
return l2_true
有没有更好的方法来做到这一点?
您也可以使用['itertools.compress'](http://docs.python.org/2/library/itertools.html#itertools.compress)。例如:'list(itertools.compress(a,b))'。但我更喜欢列表理解解决方案。 – nymk 2013-03-18 19:29:32