随机随机洗澡钥匙和价值在Python DIctionary [英] Randomly Shuffle Keys and Values in Python DIctionary

查看:159
本文介绍了随机随机洗澡钥匙和价值在Python DIctionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法随机洗牌什么键对应于什么值?我发现random.sample,但我想知道是否有更多的pythonic /更快的方式来做到这一点。



示例: a = {一个:1,两个:2,三:3}



洗牌: a_shuffled = 一:2,两:3,三:1}

解决方案

对不起,使用numpy:/更快的唯一方法是。
无论你做什么,都以某种方式争夺所有需要时间的索引,所以在C中这样做会有所帮助。此外,纯粹的随机和随机之间的区别在于您不能有重复的索引。



对不起,现在很久了 - 所以你必须做一些滚动

 例如


#为python 2.7编写,但应该能够在python 3
导入随机
导入numpy作为np
从时间导入时间


def given_seq():
#general示例
start = time()
a = {one:1,two:2,三个: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():
key = a.keys()
random.shuffle(keys)
b = dict(zip(keys,a.values()))

def np_random_shuffle():
key = a.keys()
np.random.shuffle(keys)
b = dict(zip(keys,a.values()))

def np_random_permutation )
#更简洁,使用numpy的排列选项
b = dict(zip(np.random.permutation(a.keys()),a.values()))

#如果您将数组键预先计算为numpy数组

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字典大小
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实际上减慢了
def np_random_shuffle_dstack():
keys = a.keys()
np.random.shuffle(keys)
return dict(np.dstack((keys,a.values()))[0])

如果__name __ =='__ main__':
import timeit
#我可以使用全局命名空间级别内省来自动化下面的行,但是在['given_seq','random_shuffle','np_random_shuffle'''np_r中的func
({}()格式(func),setup =从__main__导入{ }。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


使用选择/排列可能看起来更好 - 但不是更快以任何方式。不幸的是复制通常很慢,除非它是一个小尺寸 - 没有办法传递指针/引用,而不必占用一个额外的线 - 虽然我辩论,如果这使它'非pythonic'



即如果您查看禅宗的Python 或者在python会话中只需执行导入,其中一行就是:


虽然实用性是纯粹的。


所以当然可以解释:)


Is there a way to randomly shuffle what keys correspond to what values? I have found random.sample but I was wondering if there was a more pythonic/faster way of doing this.

Example: a = {"one":1,"two":2,"three":3}

Shuffled: a_shuffled = {"one":2,"two":3,"three":1}

解决方案

sorry the only way to make it faster is by using numpy :/. No matter what you do it has to somehow scramble all the indices which takes time - so doing it in C will help slightly. Also the difference between sheer random and this random is that you can't have repeated indices.

sorry it's sort of long now - so you'll have to do some scrolling

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

Using Choice/Permutation may look nicer - but it's not faster by any means. Unfortunately copying is usually slow unless it's a small size - and there's no way to pass pointers/references without it having to take up an extra line - though I debate if this makes it 'non-pythonic'

namely if you look at the Zen of Python or just do import this in a python session one of the lines is:

Although practicality beats purity.

so it's open to interpretation of course :)

这篇关于随机随机洗澡钥匙和价值在Python DIctionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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