python 将np.where数组转换为列表

vi4fp9gy  于 2023-04-19  发布在  Python
关注(0)|答案(6)|浏览(270)

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

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

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

  1. (array([ 0, 3, 6, 10, 14]),)
  2. (array([ 5, 11, 13]),)

追加后会得到一个元组列表。然而我想要的输出是这样的:

  1. [0,3,6,10,14,5,11,13]
i2byvkas

i2byvkas1#

既然有很多其他的解决方案,我将向您展示另一种方法。
您可以使用np.isin来测试数组中的好值:

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

ego6inou2#

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

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

8ehkhllq3#

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

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

r将是一个np.数组与您所要求的值。使用list(r)如果你想它作为一个列表。

p8h8hvxi

p8h8hvxi4#

使用concatenate的方法:

  1. import numpy as np
  2. l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
  3. y = np.where(l==10)[0]
  4. p = np.where(l==5)[0]
  5. k = np.concatenate((y, p))
  6. print(k) # [ 0 3 6 10 14 5 11 13]
4urapxun

4urapxun5#

在现有的一行中添加另一个。

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

Numpy可以使用&(and)、|(or)和~(not)等运算符。where函数返回一个元组,以防您传递一个布尔数组,因此索引为0。
希望这能帮上忙。

bbmckpt7

bbmckpt76#

试试这个

  1. y = [items for items in y[0]]
  2. p = [items for items in p[0]]

然后

  1. new_list = y + p

相关问题