用于列表的 python numpy.where 函数

标签 python list numpy where-clause

我有一个 python 程序,其中包含两个列表,如下例所示:

list1=["a","b","c","d"]
list2=[0,1,1,0]

有没有一种优雅的方法来创建第三个列表,它在 list2 为 1 的位置包含 list1 的元素?我正在寻找类似于数组的 numpy.where 函数的东西或更好的优雅方式:

array1=numpy.array(["a","b","c","d"])
array2=numpy.array([0,1,1,0])
array3=array1[array2==1]

是否可以创建一个与 array3 等效的 list3,在此示例中包含“b”和“c”,或者我是否必须强制转换或使用循环?

最佳答案

你可以在这里使用列表理解。

>>> array1 = ["a", "b", "c", "d"]
>>> array2 = [0, 1, 1, 0]
>>> [array1[index] for index, val in enumerate(array2) if val == 1] # Or if val
['b', 'c']

或者使用,

>>> [a for a, b in zip(array1, array2) if b]
['b', 'c']

关于用于列表的 python numpy.where 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18188638/

相关文章:

php - Python - 子字符串

python - Django 的嵌套 Meta 类是如何工作的?

python - 如何确定性地交错 N 个不同长度的异构列表?

python - 索引错误异常

python - 对屏蔽数组的有效值调用函数

python - Tensorflow:Tensordot 可重现的结果

python - 字符串替换可以写在列表理解中吗?

python - pyephem 计算仰角

r - 有没有更有效的方法在列表中用 NA 替换 NULL?

python - Numpy:检查数组中所有元素是否具有相同符号的最快方法?