布尔数组的元素列表

List of Elements to Boolean Array

假设我的清单如下: ['cat','elephant']

如何有效地将我的列表转换为布尔元素数组,其中每个索引代表我的列表中是否存在给定动物(共 10^n 只动物)?也就是说,如果猫存在,索引 x 为真,如果大象存在,索引 y 为真,但其余 10^n 均为假。

是否有 numpy 或 scipy 内置实现这种理解?

好吧,这里有几种实现此目的的方法:

地图

使用 Python 的 map 内置函数,您可以轻松做到这一点。

animal_list = ['cat', 'elephant']
your_list = ['dog', 'horse', 'cat', 'shark', 'cancer', 'elephant']
res = map(lambda item: item in animal_list, your_list)
print res

输出

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

列表理解

您可能更喜欢使用 list comprehension:

res = [ True if item in animal_list else False for item in your_list ]

NumPy 的 in1d

如果出于紧凑的原因愿意使用NumPy的数组,那么您可以这样做:

animal_list = numpy.array(['cat', 'elephant'])
your_list = numpy.array(['dog', 'horse', 'cat', 'shark', 'cancer', 'elephant'])
mask = np.in1d(your_list, animal_list)
print mask[1]

有关详细信息,请阅读 the manual

注意:如果在这种情况下animal_list恰好比your_list长,那么numpy.in1d方法会产生animal_list 作为 'target' 列表,这意味着在不同的实例中,结果数组将无法保证一致的维度。 [归功于 XLXMXNT]

原生方式

简单地循环 your_list

res = []
for animal in your_list:
    res.append(animal in animal_list)

这个:

import numpy as np

animals = np.array(['cat','elephant', 'dog'])
wanted = np.array(['cat','elephant'])
print(np.in1d(animals, wanted))

打印:

[ True  True False]
for x in range(largerlist):
    if largerlist[x] in shorterlist:
        booleanlist.append(True)
        continue
    booleanlist.append(False)