首页 > 解决方案 > 修改数组的值,其中相同大小的列表包含另一个列表的值

问题描述

我有这两个列表:

List_large = ['a','b','c','d']
List_small = ['a','c']

这个数组:

check = np.array([0]*len(List_large))
check
Out : array([0, 0, 0, 0])

我想在具有 List_small 值的 List_large 位置的数组“检查”中有 1。因此,我想最终拥有这个数组:

array([1, 0, 1, 0])

请问我该怎么办?

标签: pythonarrayslistnumpynumpy-ndarray

解决方案


作为使用三元运算符的列表理解:

>>> List_large = ['a','b','c','d']
>>> List_small = ['a','c']
>>> np.array([1 if c in List_small else 0 for c in List_large])
array([1, 0, 1, 0])

推荐阅读