[英]Randomly selecting N number of items from a list, duplicates possible
I am trying to generate a list of random items from another list b. 我正在尝试从另一个列表b生成一个随机项目的列表。 Duplicates are allowed.
允许重复。 I cannot use random.sample because N can exceed the number of items in list b.
我不能使用random.sample,因为N可以超过列表b中的项目数。
I have written some code below: 我在下面写了一些代码:
def generate_random_sequence(n):
population = []
for i in xrange(n):
b = random.choice(stuff)
population.append(b)
However i am really concerned about it's performance as it will be performed a lot of times. 但是我真的很担心它的性能,因为它会执行很多次。 Is there a method in Random library that performs this task?
随机库中是否有一种方法可以执行此任务? Or is there a more optimized way of doing this task?
还是有一种更优化的方式来执行此任务?
You can use random.choice
in numpy
library: 您可以在
numpy
库中使用random.choice
:
In [3]: np.random.choice([1,5,6],10)
Out[3]: array([6, 5, 6, 6, 6, 6, 1, 6, 1, 6])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.