基本 python 中的 Numpy.argsort() 等价物? [英] Equivalent of Numpy.argsort() in basic python?

查看:14
本文介绍了基本 python 中的 Numpy.argsort() 等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 Python 的内置函数可以在 python.array 上执行什么 argsort()numpy.array 上做了什么?

is there a builtin function of Python that does on python.array what argsort() does on a numpy.array?

推荐答案

我对上面的建议进行了计时,这是我的结果.

I timed the suggestions above and here are my results.

import timeit
import random
import numpy as np

def f(seq):
    # http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
    #non-lambda version by Tony Veijalainen
    return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]

def g(seq):
    # http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
    #lambda version by Tony Veijalainen
    return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]


def h(seq):
    #http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3382369#3382369
    #by unutbu
    return sorted(range(len(seq)), key=seq.__getitem__)


seq = list(range(10000))
random.shuffle(seq)

n_trials = 100
for cmd in [
        'f(seq)', 'g(seq)', 'h(seq)', 'np.argsort(seq)',
        'np.argsort(seq).tolist()'
        ]:
    t = timeit.Timer(cmd, globals={**globals(), **locals()})
    print('time for {:d}x {:}: {:.6f}'.format(n_trials, cmd, t.timeit(n_trials)))

输出

time for 100x f(seq): 0.323915
time for 100x g(seq): 0.235183
time for 100x h(seq): 0.132787
time for 100x np.argsort(seq): 0.091086
time for 100x np.argsort(seq).tolist(): 0.104226

此处给出了与问题大小相关的分析.

A problem size dependent analysis is given here.

这篇关于基本 python 中的 Numpy.argsort() 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆