📜  Python中的 numpy.searchsorted()

📅  最后修改于: 2022-05-13 01:55:24.046000             🧑  作者: Mango

Python中的 numpy.searchsorted()

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

代码#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]