python2 dict 乱序_在Python字典中随机乱序键和值

抱歉,用它来更快。

不管你做什么,它都必须以某种方式对所有的索引进行置乱,这需要时间——所以用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.

所以它当然是开放的解释:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值