我正在尝试创建两个具有随机长度的随机数列表(它们不必相同)。 您能告诉我为什么会收到此错误吗:
raise ValueError("样本大于总体或为负数") ValueError:样本大于总体或为负
import random
size = random.randint(6,20)
a = list(random.sample(range(1,9),size))
size = random.randint(6,10)
b = list(random.sample(range(1,7),size))
#a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []
for number in a:
for num in b:
if(number==num):
if not number in c:
c.append(number)
print(a)
print(b)
print(c)
最佳答案
你想要例如random.choices(range(1,9), k=size)
而不是 random.sample(...)
。 sample
不会重复集合中的元素,因此请求的计数必须小于集合的长度。
关于python - 为什么显示此错误: raise ValueError ("Sample larger than population or is negative") ValueError: Sample larger than population,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65472089/