python查找指定元素
- 三种方式对指定元素实现定位
- 数据准备
- 1. list:一维数组勉强用用,再高维就不要用啦
- 2. 借助numpy库
- 3. 借助torch库
三种方式对指定元素实现定位
-
本人也是新手,需要实现什么功能很多时候就是谷歌搜,一搜搜好几个才能解决问题,就像本文这个问题,我搜索到很多结果就只能找到第一个元素的索引,根本就文不是我想要的,反正大佬八成也看不到这篇文章,就随便写写啦
-
本文使用python自带功能、numpy库、pytorch库三种方式实现元素定位
-
写本文一为了方便比我还嫩的新手,二做个记录,所以很有可能我的写法繁琐了,如果您有更好的实现方法,欢迎指正,感谢!
数据准备
复制代码
1
2
3
4
5
6
7import 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]] # 二维数组
1. list:一维数组勉强用用,再高维就不要用啦
复制代码
1
2
3
4
5# 数元素个数 count_3 = list_test.count(element) >>> print(count_3) > 3
复制代码
1
2
3
4
5# 找元素出现的第一个位置 first_index_3 = list_test.index(element) >>> print(first_index_3) > 4
复制代码
1
2
3
4
5
6
7
8
9
10
11# 找元素出现所有位置 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查找还是比较麻烦的,高维非常不推荐
2. 借助numpy库
直接上二维数组,一维同理
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13list_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)
3. 借助torch库
复制代码
1
2
3
4
5
6
7
8
9
10list_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]])
最后
以上就是稳重服饰最近收集整理的关于python查找指定元素位置三种方式对指定元素实现定位的全部内容,更多相关python查找指定元素位置三种方式对指定元素实现定位内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复