抱歉,用它来更快。
不管你做什么,它都必须以某种方式对所有的索引进行置乱,这需要时间——所以用C语言做会有一点帮助。另外,完全随机和这种随机的区别在于你不能有重复的索引。在
抱歉,它现在有点长-所以你必须做一些滚动E.g.
# made for python 2.7 but should be able to work in python 3
import random
import numpy as np
from time import time
def given_seq():
#general example
start = time()
a = {“one”:1,”two”:2,”three”:3}
keys = a.keys()
random.shuffle(keys)
a = dict(zip(keys, a.values()))
#Large example
a = dict(zip(range(0,100000), range(1,100001)))
def random_shuffle():
keys = a.keys()
random.shuffle(keys)
b = dict(zip(keys, a.values()))
def np_random_shuffle():
keys = a.keys()
np.random.shuffle(keys)
b = dict(zip(keys, a.values()))
def np_random_permutation():
#more concise and using numpy’s permutation option
b = dict(zip(np.random.permutation(a.keys()), a.values()))
#if you precompute the array key as a numpy array
def np_random_keys_choice():
akeys = np.array(a.keys())
return dict(zip(akeys[np.random.permutation(len(akeys))],a.values()))
def np_random_keys_shuffle():
key_indexes = np.arange(len(a.keys()))
np.random.shuffle(key_indexes)
return dict(zip(np.array(a.keys())[key_indexes],a.values()))
#fixed dictionary size
key_indexes = np.arange(len(a.keys()))
def np_random_fixed_keys_shuffle():
np.random.shuffle(key_indexes)
return dict(zip(np.array(a.keys())[key_indexes],a.values()))
#so dstack actually slows things down
def np_random_shuffle_dstack():
keys = a.keys()
np.random.shuffle(keys)
return dict(np.dstack((keys, a.values()))[0])
if __name__==’__main__’:
import timeit
# i can use global namespace level introspection to automate the below line but it’s not needed yet
for func in [‘given_seq’, ‘random_shuffle’, ‘np_random_shuffle’, ‘np_random_permutation’, ‘np_random_keys_choice’,
‘np_random_keys_shuffle’, ‘np_random_fixed_keys_shuffle’]:
print func, timeit.timeit(“{}()”.format(func), setup = “from __main__ import {}”.format(”.join(func)), number = 200)given_seq 0.00103783607483
random_shuffle 23.869166851
np_random_shuffle 16.3060112
np_random_permutation 21.9921720028
np_random_keys_choice 21.8105020523
np_random_keys_shuffle 22.4905178547
np_random_fixed_keys_shuffle 21.8256559372
使用Choice/Permutation可能看起来更好,但无论如何也不是更快。不幸的是,复制通常是很慢的,除非它是小尺寸的-而且没有办法传递指针/引用而不需要占用额外的一行-尽管我争论这是否使它“非Python”
也就是说,如果您在python会话中查看Zen of Python或只是执行import this,其中一行是:Although practicality beats purity.
所以它当然是开放的解释:)