python中search用法_Python numpy.searchsorted()用法及代码示例

numpy.searchsorted()函数用于在排序的数组arr中查找索引,这样,如果在索引之前插入元素,arr的顺序仍将保留。在这里,二进制搜索用于查找所需的插入索引。

用法: numpy.searchsorted(arr, num, side=’left’, sorter=None)

参数:

arr :[数组]输入数组。如果sorter为None,则必须按升序对其进行排序,否则sorter必须是对其进行排序的索引数组。

num :[数组]我们要插入到arr中的值。

side :['left','right'],可选。如果为“ left”,则给出找到的第一个合适位置的索引。如果为“正确”,则返回上一个这样的索引。如果没有合适的索引,则返回0或N(其中N是a的长度)。

num :[数组,可选]整数索引数组,将数组a升序排列。它们通常是argsort的结果。

Return :[索引],与num形状相同的插入点数组。

代码1:工作

# Python program explaining

# searchsorted() function

import numpy as geek

# input array

in_arr = [2, 3, 4, 5, 6]

print ("Input array:", in_arr)

# the number which we want to insert

num = 4

print("The number which we want to insert:", num)

out_ind = geek.searchsorted(in_arr, num)

print ("Output indices to maintain sorted array:", out_ind)

输出:

Input array: [2, 3, 4, 5, 6]

The number which we want to insert: 4

Output indices to maintain sorted array: 2

代码2:

# Python program explaining

# searchsorted() function

import numpy as geek

# input array

in_arr = [2, 3, 4, 5, 6]

print ("Input array:", in_arr)

# the number which we want to insert

num = 4

print("The number which we want to insert:", num)

out_ind = geek.searchsorted(in_arr, num, side ='right')

print ("Output indices to maintain sorted array:", out_ind)

输出:

Input array: [2, 3, 4, 5, 6]

The number which we want to insert: 4

Output indices to maintain sorted array: 3

代码3:

# Python program explaining

# searchsorted() function

import numpy as geek

# input array

in_arr = [2, 3, 4, 5, 6]

print ("Input array:", in_arr)

# the numbers which we want to insert

num = [4, 8, 0]

print("The number which we want to insert:", num)

out_ind = geek.searchsorted(in_arr, num)

print ("Output indices to maintain sorted array:", out_ind)

输出:

Input array: [2, 3, 4, 5, 6]

The number which we want to insert: [4, 8, 0]

Output indices to maintain sorted array: [2 5 0]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值