栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python查找指定元素位置

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python查找指定元素位置

python查找指定元素位置

 

python查找指定元素
  • 三种方式对指定元素实现定位
    • 数据准备
    • 1. list:一维数组勉强用用,再高维就不要用啦
    • 2. 借助numpy库
    • 3. 借助torch库

 

三种方式对指定元素实现定位
  1. 本人也是新手,需要实现什么功能很多时候就是谷歌搜,一搜搜好几个才能解决问题,就像本文这个问题,我搜索到很多结果就只能找到第一个元素的索引,根本就文不是我想要的,反正大佬八成也看不到这篇文章,就随便写写啦

  2. 本文使用python自带功能、numpy库、pytorch库三种方式实现元素定位

  3. 写本文一为了方便比我还嫩的新手,二做个记录,所以很有可能我的写法繁琐了,如果您有更好的实现方法,欢迎指正,感谢!

数据准备
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]]	# 二维数组
1. list:一维数组勉强用用,再高维就不要用啦
# 数元素个数
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查找还是比较麻烦的,高维非常不推荐

2. 借助numpy库

直接上二维数组,一维同理

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)
3. 借助torch库
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]])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/834095.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号