找到元素为1的索引并转换为列表在Python中

huangapple go评论146阅读模式
英文:

Locating indices with element 1 and converting to a list in Python

问题

我有一个数组```A```。我想要找出所有包含元素1的索引并以列表形式打印出来但是我遇到了一个错误以下是预期的输出

```python
import numpy as np

A = np.array([[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0]])
A1 = np.where(A[0] == 1)
A1.tolist()
print(A1)

错误是

<module>中
    A1.tolist()

AttributeError: 'tuple' object has no attribute 'tolist'

预期的输出是

[[0, 2, 3, 5]]
英文:

I have an array A. I want to identify all indices with element 1 and print as a list. But I am getting an error. I present the expected output.

import numpy as np

A=np.array([[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0]])
A1=np.where(A[0]==1)
A1.tolist()
print(A1)

The error is

in <module>
    A1.tolist()

AttributeError: 'tuple' object has no attribute 'tolist'

The expected output is

[[0, 2, 3, 5]]

答案1

得分: 3

使用np.argwhere函数找到条件为True的索引(数组中非零的元素):

res = np.argwhere(A[0] == 1).T

[[0 2 3 5]]
英文:

Use np.argwhere to find indices where condition is True (array elements that are non-zero):

res = np.argwhere(A[0] == 1).T

[[0 2 3 5]]

答案2

得分: 1

A1 = [i for i, x in enumerate(A[0]) if x == 1]

or

A1 = list(np.where(A[0] == 1)[0])

You have an array inside an array hence A[0]

英文:
A1 = [i for i,x in enumerate(A[0]) if x == 1]

or

A1=list(np.where(A[0]==1)[0])

You have an array inside an array hence A[0]

答案3

得分: 0

数组位于元组的零索引位置,因此执行 [A1[0].tolist()],您将获得您期望的输出。

英文:

The array is at the zeroth index of the tuple, so do
[A1[0].tolist()] and you will have your expected output.

答案4

得分: 0

正如其他人指出的,你有一个二维数组,所以该函数返回每个维度的数组元组。然而,这并不能得到你期望的输出。有两种可能的方法可以实现这一点,一种是经典版本,另一种是基于你的输入数据(0和1)可以使用nonzero方法来完成的numpy版本:

# 经典版本
A1 = [idx for idx, v in enumerate(A[0]) if v == 1]

# numpy版本
A1 = np.nonzero(A[0])

nonzero也可以用于应用不同的条件来获取索引,比如等于2的情况:

np.nonzero(A[0] == 2)

你可以在这里了解更多关于nonzero的用法:numpy.nonzero文档

英文:

As others have pointed out, you have a 2 dimensions array, so the function returns a tuple of array for each dimension. Still, this does not bring your desired output.

There 2 possible ways to achieve this, a classic version and the numpy version - which based on your input data (0 and 1) can be done with nonzero method:

# the classic version
A1 = [idx for idx, v in enumerate(A[0]) if v == 1]

# the numpy version
A1 = np.nonzero(A[0])

The nonzero can also be used to apply a different condition to get the indexes, let's say equal to 2.

np.nonzero(A[0] == 2)

You can read more about the nonzero use cases here: numpy.nonzero doc.

huangapple
  • 本文由 发表于 2023年3月7日 15:24:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定