【发布时间】:2021-11-11 14:29:12
【问题描述】:
我编写了一个代码来随机获取一组人。目的是当一个人已经被随机选择时,程序应该删除他。我使用了random.sample() 函数,当我达到 5 时它对n=1,2,3,4 工作得很好,它给了我一个错误,直到现在我试图了解这个函数背后发生了什么。任何解释和提示都会有所帮助。谢谢!
import random
ma_list =["anne","aline","gros","eve","armand","yves","elv","allo","sonia","luc","marc","jules","kevin"]
#this will contain an occurence of our list
maListOc = ma_list
#this list will contain our random list
random_list = None
groupe = 1
#for each element in ma_list, we randome and put into our variable
for i in ma_list:
random_list = random.sample(ma_list, 5)
#then we remove data already randomize in our list, but the complexity is high for this little program
for element in random_list:
ma_list.remove(element)
print("Goupe N°:",groupe)
#and we finally print our randomized list
print(random_list)
print("______________________________")
groupe += 1
print(maListOc)
这是输出:
Goupe N°: 1
['aline', 'gros', 'armand', 'sonia', 'anne']
______________________________
Goupe N°: 2
['kevin', 'allo', 'eve', 'elv', 'marc']
______________________________
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-c2d13d61c8d1> in <module>
8 #for each element in ma_list, we randome and put into our variable
9 for i in ma_list:
---> 10 random_list = random.sample(ma_list, 5)
11 #then we remove data already randomize in our list, but the complexity is high for this little program
12 for element in random_list:
~\anaconda3\lib\random.py in sample(self, population, k)
361 n = len(population)
362 if not 0 <= k <= n:
--> 363 raise ValueError("Sample larger than population or is negative")
364 result = [None] * k
365 setsize = 21 # size of a small set minus size of an empty list
ValueError: Sample larger than population or is negative
【问题讨论】:
-
我不确定有什么不清楚的地方。您正在从
ma_list中删除项目,直到它少于 5 个项目。那你就不能再随机选择5个了。 -
经过 2 次迭代,只剩下 3 个名称。所以样本不能从 3 个列表项中取出 5 个名称。
-
我现在明白了,所以如果我想每组有五个人,我应该增加项目的数量。谢谢
-
当我这样做的时候,我只是在说如果我想在每个组中有 5 个或更多,会发生什么。大声笑