我需要从列表中挑选出"x“个不重复的随机数。例如:
all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15]如何选择像[2, 11, 15]而不是[3, 8, 8]这样的列表
发布于 2011-06-27 22:33:56
这正是random.sample()所做的。
>>> random.sample(range(1, 16), 3)
[11, 10, 2]编辑:我几乎可以肯定这不是你所要求的,但我被要求添加这样的评论:如果你想从其中获取样本的总体包含重复项,你必须首先删除它们:
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)发布于 2011-06-27 22:35:17
如下所示:
all_data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
from random import shuffle
shuffle(all_data)
res = all_data[:3]# or any other number of items或者:
from random import sample
number_of_items = 4
sample(all_data, number_of_items)如果all_data可能包含重复条目,请先修改代码以删除重复条目,然后使用shuffle或sample:
all_data = list(set(all_data))
shuffle(all_data)
res = all_data[:3]# or any other number of items发布于 2011-06-27 22:37:08
其他人则建议您使用random.sample。虽然这是一个有效的建议,但每个人都忽略了一个微妙之处:
如果总体包含重复,则每次出现都是样本中可能的选择。
因此,您需要将列表转换为一个集合,以避免重复值:
import random
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
random.sample(set(L), x) # where x is the number of samples that you wanthttps://stackoverflow.com/questions/6494508
复制相似问题