本人也是新手,需要实现什么功能很多时候就是谷歌搜,一搜搜好几个才能解决问题,就像本文这个问题,我搜索到很多结果就只能找到第一个元素的索引,根本就文不是我想要的,反正大佬八成也看不到这篇文章,就随便写写啦
本文使用python自带功能、numpy库、pytorch库三种方式实现元素定位
写本文一为了方便比我还嫩的新手,二做个记录,所以很有可能我的写法繁琐了,如果您有更好的实现方法,欢迎指正,感谢!
import numpy as np
import torch
element = 3 # 要找的元素
list_test = [1, 2, 2, 2, 3, 3, 4, 5, 6, 7, 3] # 一维数组
list_test_2 = [[1, 2, 3, 4, 3, 4, 6, 1], [1, 3, 2, 2, 3, 5, 6, 3]] # 二维数组
# 数元素个数
count_3 = list_test.count(element)
>>> print(count_3)
> 3
# 找元素出现的第一个位置
first_index_3 = list_test.index(element)
>>> print(first_index_3)
> 4
# 找元素出现所有位置
index = []
current_pos = 0
for _ in range(list_test.count(element)):
new_list = list_test[current_pos:]
_index = new_list.index(element)
index.append(current_pos + _index)
current_pos += new_list.index(element)+1
>>> print(index)
>[4, 5, 10]
用list查找还是比较麻烦的,高维非常不推荐
直接上二维数组,一维同理
list_numpy = np.array(list_test_2)
list_numpy_index_3 = np.where(list_numpy == element)
list_numpy_index_3_matrix = np.dstack((list_numpy_index_3[0], list_numpy_index_3[1])).squeeze()
# 第三行代码作用是将第二行代码得到的两个array拼接成一个矩阵,一维数组查找不需要这行
>>> print(list_numpy_index_3)
> (array([0, 0, 1, 1, 1], dtype=int64), array([2, 4, 1, 4, 7], dtype=int64))
>>> print(list_numpy_index_3_matrix)
>array([[0, 2],
[0, 4],
[1, 1],
[1, 4],
[1, 7]], dtype=int64)
list_torch = torch.tensor(list_test_2)
list_torch_index_3 = torch.nonzero(torch.where(list_torch == element, torch.tensor(element), torch.tensor(0)))
# 原理就是借助nonzero函数,找到所有非0元素,首先是需要将不需要的元素变为0
>>> print(list_torch_index_3)
> tensor([[0, 2],
[0, 4],
[1, 1],
[1, 4],
[1, 7]])