1

どのキーがどの値に対応するかをランダムにシャッフルする方法はありますか? random.sample を見つけましたが、これを行うためのよりPythonic/高速な方法があるかどうか疑問に思っていました。

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

シャッフル:a_shuffled = {"one":2,"two":3,"three":1}

4

2 に答える 2

6
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.sampleusingはより単純ですが、 usingrandom.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
于 2013-08-01T15:03:21.967 に答える