random.randint和random.sample之间的区别

时间:2015-12-10 20:50:27

标签: random

我已经阅读了每个文档,并发现有点难以理解这里的差异。我使用random.sample编写了这段代码:

import random

print "Welcome to the guessing game."

number_of_guesses = 1
correct_number = random.sample(range(1,101),1)

while number_of_guesses < 999:

    user_choice = int(input("Guess a number between 1 and 100: "))

    if user_choice == correct_number:
        print "You guessed the number in %s tries." % number_of_guesses

    elif user_choice < correct_number:
        print "Too low, guess again."
        number_of_guesses += 1

    elif user_choice > correct_number:
        print "Too high, guess again."
        number_of_guesses += 1

当我运行此代码并输入一个数字时,我得到的数据太低,再次猜测。&#34;无论我输入什么号码,但是当我使用random.randomint时,它可以正常工作。谁能解释为什么会这样?

1 个答案:

答案 0 :(得分:3)

random.sample(range(1,101),1)将返回包含整数的单例列表,而random.randint(1,100)将直接返回整数本身。请注意,random.randint是包含边界(即它可以返回任一端点)

您也可以使用random.choice(range(1, 101))来获取整数。无论如何,我认为randint是最快的选择。