【问题标题】:Loop an answer Python循环一个答案 Python
【发布时间】:2015-03-01 20:39:43
【问题描述】:

我有一个想要循环 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:样本大于总体
我必须填充什么?我需要另一个变量吗? 提前致谢。 问候托马斯

【问题讨论】:

    标签: python loops random


    【解决方案1】:

    我假设你想要的是:

    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)
    

    【讨论】:

    • 当我使用您的第一个替代方案时,我收到错误:NameError: name 'xrange' is not defined。我需要用它做一个变量吗?像'var xrange'?
    • 是的,我已经习惯了 python 2,那是我的错。大概您使用的是某些版本的 python 3,请尝试使用 range。
    • 是的,这创造了奇迹。我应该告诉我我正在使用 Python 3...非常感谢您的帮助。 //托马斯
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      我认为您需要使用 xrange(bottom,top) 而不仅仅是 (bottom,top) 这将填充从底部到顶部的总体,然后 random.sample(xrange(bottom,top),10) 将现在能够返回从已填充的元素中选择的 10 个随机元素的列表,而原始总体保持不变。

      【讨论】:

        【解决方案4】:

        只需使用一个while循环:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-29
          • 1970-01-01
          • 1970-01-01
          • 2021-12-20
          相关资源
          最近更新 更多