Geo*_*ge 50 python random list
我需要从列表中挑出"x"个非重复的随机数.例如:
all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15]
Run Code Online (Sandbox Code Playgroud)
我如何选择一个喜欢[2, 11, 15]
和不喜欢的列表[3, 8, 8]
?
Sve*_*ach 78
这正是做什么的random.sample()
.
>>> random.sample(range(1, 16), 3)
[11, 10, 2]
Run Code Online (Sandbox Code Playgroud)
编辑:我几乎可以肯定这不是你提出的问题,但是我被推荐包括这个评论:如果你想从中获取样本的人口包含重复项,你必须先删除它们:
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)
Run Code Online (Sandbox Code Playgroud)
其他人建议您使用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 want
Run Code Online (Sandbox Code Playgroud)
像这样:
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
Run Code Online (Sandbox Code Playgroud)
要么:
from random import sample
number_of_items = 4
sample(all_data, number_of_items)
Run Code Online (Sandbox Code Playgroud)
如果all_data可能包含重复项,则可以修改代码以先删除重复项,然后使用shuffle或sample:
all_data = list(set(all_data))
shuffle(all_data)
res = all_data[:3]# or any other number of items
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30849 次 |
最近记录: |