Python中的随机采样

0 投票
4 回答
4929 浏览
提问于 2025-04-18 07:00

你好,请看下面的代码,当大小大于5时,会出现下面的错误。有没有其他的随机函数可以在Python 2.7中生成,比如说6个或更多不同的样本,这样人口就会有6个列表添加到其中。谢谢!

import random as rand

population = []
individual = [1,2,3,4,5]
size = 5

for ind in individual:
        population.append((rand.sample(individual, size)))

print "pop", population

#output
pop =  [[1, 3, 5, 2, 4], [3, 4, 5, 2, 1], [3, 1, 2, 4, 5], [1, 5, 3, 4, 2], [1, 5, 3, 2, 4]] 
#Error Message
Traceback (most recent call last):
  File "C:/Users/AMAMIFE/Desktop/obi/tt.py", line 10, in <module>
    population.append((rand.sample(individual, size)))
  File "C:\Python27\x86\lib\random.py", line 321, in sample
    raise ValueError("sample larger than population")
ValueError: sample larger than population

4 个回答

0

试试这个:

import random as rand
individual = 5
population = []
size = 5

for ind in individual:
        population.append((rand.sample(xrange(individual), size)))

print "pop", population
1

使用列表推导式:

from random import choice
pop = [[choice(individual) for _ in range(size)] for _ in range(size)]

只要 individual 不是一个空的序列,这个方法就可以正常工作。

注意:我用 size 这个变量来表示每个子列表的大小和子列表的数量。如果你想要5个包含10个值的列表,你需要相应地调整这个变量。

编辑:缩短了一些变量名,以便更容易阅读。

1

你正在修改错误的变量;你应该调整的是 for 循环,而不是 sample 的参数:

size = len(individual)
pop_size = 6
for _ in range(pop_size):
    population.append(rand.sample(individual, size))

注意,pop_size 是要添加到 population 中的子列表数量,而 sizeindividual 的长度。你也可以考虑使用:

for _ in range(pop_size):
    rand.shuffle(individual)
    population.append(individual[:])

也就是说,在每次循环中随机打乱 individual,然后把它的一个副本添加到 population 中。

4

你在这里使用 sample 的方式似乎不太对。random.sample(a_sequence, n) 是从 a_sequence 中随机选择 n 个对象。举个例子:

>>> import random
>>> my_list = range(5)
>>> random.sample(my_list, 3)
[0, 3, 2]
>>> random.sample(my_list, 3)
[4, 1, 0]
>>> random.sample(my_list, 3)
[2, 0, 4]
>>> random.sample(my_list, 3)
[4, 0, 2]
>>> random.sample(my_list, 3)
[1, 4, 3]

从一个有5个项目的列表中尝试抽取6个项目是没有意义的。因为你抽出5个之后,就没有第六个可以抽了。

当你说想从一个大小为5的列表中抽取5个项目时,其实就是在说你想要所有的项目,只是顺序是随机的。如果你想要从中获取 n 个,可以试试使用 itertools.permutations

>>> import random
>>> import itertools
>>> my_list = range(5)
>>> random.sample(list(itertools.permutations(my_list)), 5)
[(4, 2, 1, 3, 0), (3, 0, 2, 4, 1), (2, 3, 0, 4, 1), (4, 3, 0, 1, 2), (4, 0, 3, 2, 1)]
>>> random.sample(list(itertools.permutations(my_list)), 6)
[(0, 2, 1, 4, 3), (1, 2, 4, 0, 3), (1, 0, 3, 2, 4), (2, 1, 4, 3, 0), (0, 3, 2, 1, 4), (4, 2, 0, 1, 3)]
>>> random.sample(list(itertools.permutations(my_list)), 7)
[(4, 3, 1, 2, 0), (3, 0, 1, 2, 4), (2, 0, 1, 3, 4), (4, 2, 3, 1, 0), (0, 4, 1, 3, 2), (3, 0, 2, 1, 4), (0, 1, 2, 3, 4)]

撰写回答