【数组排序返回索引-python和c++的实现】教程文章相关的互联网学习教程文章

探究数组排序提升Python程序的循环的运行效率的原因

早上我偶然看见一篇介绍两个Python脚本的博文,其中一个效率更高。这篇博文已经被删除,所以我没办法给出文章链接,但脚本基本可以归结如下: fast.pyimport time a = [i for i in range(1000000)] sum = 0 t1 = time.time() for i in a:sum = sum + i t2 = time.time() print t2-t1 slow.pyimport time from random import shuffle a = [i for i in range(1000000)] shuffle(a) sum = 0 t1 = time.time() for i in a:sum = sum + ...

数组排序返回索引-python和c++的实现【代码】

返回一个数组排序后的索引经常在项目中用到,所以这里总结一下c++和python两种语言的实现。 Python#!/usr/local/bin/python3a=[2,3,4,5,63,4,32,3]# ascending #sorted sorted_indx = [idx for idx,v in sorted(enumerate(a), key=lambda x: x[1])] print("ascending sorted:", sorted_indx)#numpy import numpy as np sorted_indx = np.argsort(a) print("ascending argsort:", sorted_indx)# descending #sorted sorted_indx = ...

python – 将数组排序到索引数组指定的bin中的最有效方法?【代码】

任务示例:data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) idx = np.array([2, 0, 1, 1, 2, 0, 1, 1, 2])预期结果:binned = np.array([2, 6, 3, 4, 7, 8, 1, 5, 9])约束: >应该快.>应为O(n k),其中n是数据长度,k是bin的数量.>应该是稳定的,即保留在箱内的订单. 明显的解决方案data[np.argsort(idx, kind='stable')]是O(n log n). O(n k)解决方案def sort_to_bins(idx, data, mx=-1):if mx==-1:mx = idx.max() + 1cnts = np.zero...

数组排序 - 相关标签