在 python 中对列表的 n 个随机排列进行采样

sample n random permutations of a list in python

我有一个值列表,例如:

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我需要可重现地 return n 随机洗牌这个列表。

理想情况下,我需要一个带种子的函数 f(lst, samples = 2, seed = 1234) -> return 列表的两次洗牌 lst 例如:

[5, 7, 1, 6, 2, 8, 0, 4, 3, 9]
[8, 7, 3, 0, 1, 4, 5, 9, 6, 2]

重复执行此函数(使用相同的种子)将 return 得到相同的两个列表。

您可以使用np.copy

import numpy as np

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


def shuffle_list(arr:list,samples:int,seed:int):
    np.random.seed(seed)
    res = []
    for i in range(samples):
        arr_copy=np.copy(arr)
        np.random.shuffle(arr_copy)
        res.append(arr_copy)
    return res


#test
print(shuffle_list(lst,2,1234))

输出:

[array([7, 2, 9, 1, 0, 8, 4, 5, 6, 3]), array([7, 3, 5, 1, 4, 8, 0, 2, 6, 9])]

这在没有 numpy 的情况下有效:

import sys
import random

some_seed = 123  # change this to get different shuffles

def n_shuffles(lst, n):
    r = random.Random(some_seed)
    for _ in range(n):
        _l = lst[:]
        r.shuffle(_l)
        yield _l


l = list(range(10))
>>> [*n_shuffles(l, 3)]
[[8, 7, 5, 9, 2, 3, 6, 1, 4, 0], [7, 6, 3, 4, 1, 0, 2, 5, 9, 8], [1, 8, 5, 6, 4, 7, 9, 0, 2, 3]]
>>> [*n_shuffles(l, 3)]
[[8, 7, 5, 9, 2, 3, 6, 1, 4, 0], [7, 6, 3, 4, 1, 0, 2, 5, 9, 8], [1, 8, 5, 6, 4, 7, 9, 0, 2, 3]]

好吧,这不是 完全 重复,但提议的主题几乎表明重新设置 seed() 是关键:

import random

def shuffles(l,n):
  random.seed(4) # just the same one as in the referred topic
  return [random.sample(l,k=len(l)) for i in range(n)]

print(shuffles([1,2,3,4],3))
print("again:")
print(shuffles([1,2,3,4],3))

将生成

[[2, 4, 1, 3], [4, 1, 3, 2], [1, 2, 3, 4]]                            
again:                                                                
[[2, 4, 1, 3], [4, 1, 3, 2], [1, 2, 3, 4]]

您可以使用 [:]listnumpy.random.shuffle 创建副本 按如下方式随机播放 list

import numpy as np

def shuffle_lst(lst, samples = 2, seed = 1234):
    np.random.seed(seed)
    L_lst = [lst[:] for i in range(samples)]
    [np.random.shuffle(L_lst[i]) for i in range(samples)]
    return L_lst

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f'Iter 1: {shuffle_lst(lst)}')
print(f'Iter 2: {shuffle_lst(lst)}')
print(f'Iter 2: {shuffle_lst(lst)}')

输出:

Iter 1: [[7, 2, 9, 1, 0, 8, 4, 5, 6, 3], [7, 3, 5, 1, 4, 8, 0, 2, 6, 9]]
Iter 2: [[7, 2, 9, 1, 0, 8, 4, 5, 6, 3], [7, 3, 5, 1, 4, 8, 0, 2, 6, 9]]
Iter 2: [[7, 2, 9, 1, 0, 8, 4, 5, 6, 3], [7, 3, 5, 1, 4, 8, 0, 2, 6, 9]]