Skip to main content
 首页 » 编程设计

python之在 Python 字典中随机随机排列键和值

2025年05月04日11soundcode

有没有办法随机打乱哪些键对应哪些值?我找到了 random.sample 但我想知道是否有更 pythonic/更快的方法来做到这一点。

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

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

请您参考如下方法:

In [47]: import random 
 
In [48]: keys = a.keys() 
 
In [49]: values = a.values() 
 
In [50]: random.shuffle(values) 
 
In [51]: a_shuffled = dict(zip(keys, values)) 
 
In [52]: a_shuffled 
Out[52]: {'one': 2, 'three': 1, 'two': 3} 

或者,更简洁的是:

In [56]: dict(zip(a.keys(), random.sample(a.values(), len(a)))) 
Out[56]: {'one': 3, 'three': 2, 'two': 1} 

(但我想这就是您已经想出的解决方案。)


请注意,虽然使用 random.sample 更简洁,但使用 random.shuffle 会更快一些:

import random 
import string 
def using_shuffle(a): 
    keys = a.keys() 
    values = a.values() 
    random.shuffle(values) 
    return dict(zip(keys, values)) 
 
def using_sample(a): 
    return dict(zip(a.keys(), random.sample(a.values(), len(a)))) 
 
N = 10000 
keys = [''.join(random.choice(string.letters) for j in range(4)) for i in xrange(N)] 
a = dict(zip(keys, range(N))) 
 
In [71]: %timeit using_shuffle(a) 
100 loops, best of 3: 5.14 ms per loop 
 
In [72]: %timeit using_sample(a) 
100 loops, best of 3: 5.78 ms per loop