循环回答 Python

Loop an answer Python

我有一个答案,我想循环 10 次。 代码现在看起来像这样:

top = int(input("Please tell us the highest number in the range: "))
bottom = int(input("Tell us the lowest number in the range: "))
print("Batman picks the number",random.randint(bottom,top),"from the range between",bottom,"and",top)

这给我留下了答案:
请告诉我们范围内的最高数字:100
告诉我们范围内的最小数字:10
蝙蝠侠从 10 到 100 之间选择数字 57

现在我想让蝙蝠侠从范围内随机选择10个数字。我是这样想的:

print("Batman picks the number",random.sample((bottom,top), 10),"from the range between",bottom,"and",top)

问题是我收到一条错误消息: ValueError:样本大于总体
我必须填充什么?我需要另一个变量吗? 提前致谢。 问候托马斯

只需使用一个 while 循环:

num = 10
while num>0:
    print("Batman picks the number",random.randint(bottom,top),"from the range between",bottom,"and",top)
    num -= 1

您收到关于人口的错误,因为您使用不当。它不期望下限和上限范围的元组,而是要从中随机选择的元素列表。应该这样使用:

>>> import random
>>> random.sample(range(0, 20), 10)
[7, 4, 8, 5, 19, 1, 0, 12, 17, 11]
>>> 

或者将任何项目列表作为第一个变量。

我假设你想要的是:

print("Batman picks the number",random.sample(range(bottom,top), 10),"from the range between",bottom,"and",top)

也就是说,我假设您希望在没有替换的情况下进行采样。如果你想为每个数字打印一行,你可以这样做:

for number in random.sample(range(bottom,top):
    print("Batman picks the number", number, 10),"from the range between",bottom,"and",top)

我认为您需要使用 xrange(bottom,top) 而不仅仅是 (bottom,top) 这会从下到上填充人口,然后 random.sample(xrange(bottom,top) ,10) 现在能够 return 从填充的元素中选择 10 个随机元素的列表,而原始填充不变。