将np.where数组转换为列表

时间:2018-04-17 15:27:19

标签: python arrays list numpy

我尝试使用np.where获取数组的索引,并希望以这样的方式连接列表,即它给出了一个列表。可能吗?

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
y= np.where(l==10)
p=np.where(l==5)

如果我打印y和p,他们会给我

(array([ 0,  3,  6, 10, 14]),)

(array([ 5, 11, 13]),)

在追加它时会产生一个元组列表。但是我想要的输出是:

[0,3,6,10,14,5,11,13]

5 个答案:

答案 0 :(得分:1)

编辑:由于还有很多其他解决方案,我将以另一种方式向您展示。

您可以使用np.isin来测试数组中的良好值:

goovalues = {5, 10}
np.where(np.isin(l, goodvalues))[0].tolist() #  [0, 3, 6, 10, 14, 5, 11, 13]

答案 1 :(得分:1)

您可以使用y[0]p[0]访问列表,然后附加结果。只需添加以下行:

r = np.append(y[0], p[0])

r将是您提出的值的np.array。如果您希望将其作为列表,请使用list(r)

答案 2 :(得分:1)

您可以concatinate两个数组,然后将结果转换为列表:

result = np.concatenate((y[0], p[0])).tolist()

答案 3 :(得分:0)

使用concatenate执行此操作的方法:

import numpy as np

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
y = np.where(l==10)[0]
p = np.where(l==5)[0]
k = np.concatenate((y, p))

print(k) # [ 0  3  6 10 14  5 11 13]

答案 4 :(得分:0)

在一行中添加现有的其他内容。

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])

y = np.where((l == 10)|(l == 5))[0]

Numpy与&等运营商合作。 (和),| (或),和〜(不)。 where函数返回一个元组,以防你传递一个布尔数组,因此传递索引0。

希望这有帮助。

相关问题