数组排序返回索引-python和c++的实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了数组排序返回索引-python和c++的实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1764字,纯文字阅读大概需要3分钟。
内容图文
![数组排序返回索引-python和c++的实现](/upload/InfoBanner/zyjiaocheng/644/570a4df788ae48fab5a1f4f29c4559e2.jpg)
返回一个数组排序后的索引经常在项目中用到,所以这里总结一下c++和python两种语言的实现。
Python
#!/usr/local/bin/python3 a=[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 = [idx for idx,v in sorted(enumerate(a), key=lambda x: x[1], reverse=True)] print("descending sorted:", sorted_indx) #numpy import numpy as np sorted_indx = np.argsort(-np.array(a)) print("descending argsort:", sorted_indx) ''' output ascending sorted: [0, 1, 7, 2, 5, 3, 6, 4] ascending argsort: [0 1 7 2 5 3 6 4] descending sorted: [4, 6, 3, 2, 5, 1, 7, 0] descending argsort: [4 6 3 2 5 1 7 0] '''
c++
#include <vector> #include <iostream> using namespace std; template<typename T> vector<int> sort_indexes(const vector<T> & v, bool reverse=false) { // initialize original index locations vector<int> idx(v.size()); for (int i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v if(reverse) { sort(idx.begin(), idx.end(), [& v](int i1, int i2) {return v[i1] > v[i2];}); }else{ sort(idx.begin(), idx.end(), [& v](int i1, int i2) {return v[i1] < v[i2];}); } return idx; } int main() { int arr[] = {2,3,4,5,63,4,32,3}; vector<int> l(arr, arr+8); vector<int> sorted_indx; sorted_indx = sort_indexes(l); cout << "ascending sorted: "; for(auto e : sorted_indx) { cout << e << " "; } cout << endl; sorted_indx = sort_indexes(l, true); cout << "descending sorted: "; for(auto e : sorted_indx) { cout << e << " "; } cout << endl; return 0; } /*output ~$ g++ -std=c++11 index_sort.cpp -o test ~$ ./test ascending sorted: 0 1 7 2 5 3 6 4 descending sorted: 4 6 3 2 5 1 7 0 */
内容总结
以上是互联网集市为您收集整理的数组排序返回索引-python和c++的实现全部内容,希望文章能够帮你解决数组排序返回索引-python和c++的实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。