您如何选择"x" Python列表中唯一数字的个数? [英] How do you pick "x" number of unique numbers from a list in Python?

查看:69
本文介绍了您如何选择"x" Python列表中唯一数字的个数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从列表中挑选出"x"个非重复的随机数.例如:

I need to pick out "x" number of non-repeating, random numbers out of a list. For example:

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]的列表?

How do I pick out a list like [2, 11, 15] and not [3, 8, 8]?

推荐答案

random.sample() .

>>> random.sample(range(1, 16), 3)
[11, 10, 2]

编辑:我几乎可以肯定这不是您的要求,但我被迫加入此评论:如果要从中采样的总体中包含重复项,则必须将其删除首先:

Edit: I'm almost certain this is not what you asked, but I was pushed to include this comment: If the population you want to take samples from contains duplicates, you have to remove them first:

population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)

这篇关于您如何选择"x" Python列表中唯一数字的个数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆