首页 > 解决方案 > random.choice 在计算其参数时存在问题

问题描述

random.choice我在随机模块中有一个问题。所以在这里我有一个漂亮的代码块:

for trap in range(11):
    leftorright = raw_input("")
    if leftorright == "left" or "right":
        leftchoice = random.choice(True, False)
        if leftchoice:
            print "You don't feel anything on your legs, so you think you're okay."
        else:
            print "You feel a sharp pain on your %s leg." %(random.choice("left", "right"))
    else:
        print sorrycommand

所以这里的问题是两个random.choice实例(leftchoice = random.choice(True, False)print "You feel a sharp pain on your %s leg." %(random.choice("left", "right")))给了我这个错误:

Traceback (most recent call last):
  File "main.py", line 408, in <module>
    startmenuchoice() 
  File "main.py", line 404, in startmenuchoice
    room7()
  File "main.py", line 386, in room7
    leftchoice = random.choice(True, False)
TypeError: choice() takes exactly 2 arguments (3 given)

现在,直接进入这里的真实情况:TypeError: choice() takes exactly 2 arguments (3 given)

它在错误中说给出了3 个参数,但是如果您查看错误代码,显然只给出了2 个参数(需要适当数量的参数)。有人可以帮我吗?

旁注:

  1. 我将在评论中提供所需的任何其他信息,因为我不太会考虑所需的每一个信息。
  2. 我正在使用网站 repl.it,它是一个在线 IDE 和编译器。也许这可能与它有关?

标签: pythonrandom

解决方案


random.choice不接受多个参数;它需要一个序列从中选择一个值。

leftchoice = random.choice([True, False])

random模块定义了一个类,Random它封装了一个随机数生成器。你创建一个实例,用一个可选的种子来初始化它,然后调用它的方法来获取各种随机值。

gen = random.Random(2382948)
x = gen.choice([True, False])

这非常适合测试,因为您可以使用相同的种子创建可重现的随机序列。但是,在一般使用中,您可能不关心种子并且对一些默认种子(这里是基于返回值的值os.urandom)感到满意。为了方便该用例,模块在导入时random创建一个模块级实例:Random

_inst = Random()

并为该实例的方法创建一堆模块级别名:

...
choice = _inst.choice

因此random.choice,与其作为一个接受一个序列参数的函数,它实际上是一个绑定方法,其底层的未绑定方法接受两个参数(一个实例和一个序列),因此只需要一个。(请记住,它_inst.choice([True, False])解析为 Random.choice(_inst, [True, False])`。)

您看到的错误消息random.choice(True, False)是由于您正在有效地尝试调用Random.choice,定义为

def choice(self, seq):
    ...

as _inst.choice(True, False)or ( Random.choice(_inst, True, False)),现在应该清楚你有一个参数太多了。


推荐阅读