从有替代者的列表中随机选择

2024-05-17 04:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,如下所示:

a = [[1,2],[2,3]]

我想用a中给定大小的替换项创建一个随机列表。^{}方法只接受1D数组。我可以编写自己的函数来实现这一点,但是否已经有了一种优化的方法?

预期输出

[[1,2],[1,2],[2,3],[2,3]] 
// the size (4 here) has to be a parameter passed to the function

Tags: theto方法函数列表sizehereparameter
3条回答

使用numpy:

size = 4
a = np.array([[1,2],[2,3]])
b = np.random.randint(len(a), size = size)
a[b,:]

Out[93]:
array([[2, 3],
       [2, 3],
       [2, 3],
       [1, 2]])

您只需重复调用the standard library's ^{}。不需要numpy

>>> list_of_lists = [[1, 2], [2, 3]]
>>> sample_size = 4
>>> [random.choice(list_of_lists) for _ in range(sample_size)]
[[1, 2], [2, 3], [1, 2], [1, 2]]

这是^{}的另一种选择,它不需要替换就可以工作,并且允许您选择一个大于原始总体大小的“样本”。

从Python 3.6开始,您可以直接使用^{}

random.choices(list_of_lists, k=sample_size)
## [[1, 2], [3, 4], [3, 4], [1, 2]]

一个粗略的基准表明,与列表理解方法相比,这种方法在不同的样本量上似乎更有效。

>>> list_of_lists = [[1, 2], [3, 4]]
>>> sample_size = 4

>>> %timeit [random.choice(list_of_lists) for _ in range(sample_size)]
4.49 µs ± 20.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

>>> %timeit random.choices(list_of_lists, k=sample_size)
1.99 µs ± 14.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

>>> list_of_lists *= 100
>>> sample_size *= 1000

>>> %timeit [random.choice(list_of_lists) for _ in range(sample_size)]
3.54 ms ± 28.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit random.choices(list_of_lists, k=sample_size)
927 µs ± 1.39 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

相关问题 更多 >