如果区域设置不受关注,在Python中对字符串进行排序的最快方法是什么?

xia*_*dai 5 python sorting string

我试图找到一种快速的方法来在Python中对字符串进行排序,并且语言环境是一个无关紧要的问题,即我只想根据底层字节对词汇进行排序.这非常适合基数排序.这是我的MWE

import numpy as np
import timeit

# randChar is workaround for MemoryError in mtrand.RandomState.choice
# http://stackoverflow.com/questions/25627161/how-to-solve-memory-error-in-mtrand-randomstate-choice
def randChar(f, numGrp, N) :
   things = [f%x for x in range(numGrp)]
   return [things[x] for x in np.random.choice(numGrp, N)]

N=int(1e7)
K=100
id3 = randChar("id%010d", N//K, N)   # small groups (char)
timeit.Timer("id3.sort()" ,"from __main__ import id3").timeit(1) # 6.8 seconds
Run Code Online (Sandbox Code Playgroud)

你可以看到它需要6.8秒,这比下面的R的基数排序慢近10倍.

N = 1e7
K = 100
id3 = sample(sprintf("id%010d",1:(N/K)), N, TRUE)
system.time(sort(id3,method="radix"))
Run Code Online (Sandbox Code Playgroud)

我知道Python .sort()不使用基数排序,是否有某个实现允许我像R一样对字符串进行排序?

AFAIK既有R又有Python"实习"字符串,因此R中的任何优化也可以在Python中完成.

"基数排序字符串python"的顶级谷歌结果是这个要点,在我的测试数组上排序时产生错误.

xia*_*dai 0

Jeremy Mets 在这篇博文的评论中表示,Numpy 可以通过将数组转换为np.araray. 这确实提高了性能,但仍然比 Julia 的实现慢。

import numpy as np
import timeit

# randChar is workaround for MemoryError in mtrand.RandomState.choice
# http://stackoverflow.com/questions/25627161/how-to-solve-memory-error-in-mtrand-randomstate-choice
def randChar(f, numGrp, N) :
   things = [f%x for x in range(numGrp)]
   return [things[x] for x in np.random.choice(numGrp, N)]

N=int(1e7)
K=100
id3 = np.array(randChar("id%010d", N//K, N))   # small groups (char)
timeit.Timer("id3.sort()" ,"from __main__ import id3").timeit(1) # 6.8 seconds
Run Code Online (Sandbox Code Playgroud)