brb*_*brb 1 python random arguments
我在下面的掷骰子功能中犯了一个简单的错误:
import random
def rollDie():
return random.choice(1,2,3,4,5,6)
print(rollDie())
Run Code Online (Sandbox Code Playgroud)
我知道我需要将序列作为列表或元组传递,但我对以下错误消息更加好奇.
Traceback (most recent call last):
File "Lecture 5.2 -- stochastic - die roll example.py", line 8, in <module>
print(rollDie())
File "Lecture 5.2 -- stochastic - die roll example.py", line 6, in rollDie
return random.choice(1,2,3,4,5,6)
TypeError: choice() takes 2 positional arguments but 7 were given
Run Code Online (Sandbox Code Playgroud)
消息说"choice()需要2个位置参数,但7个被给出".
但是文档只显示了一个参数(序列). https://docs.python.org/3/library/random.html
第二个论点是什么(在我的案例中是第七个)?这是种子(我没有指定的种子是由时钟初始化的)?
choice()是模块维护的隐藏Random()实例的方法random.因为它是一个方法,所以它有两个参数:self和可从中进行选择的迭代.
从模块文档:
此模块提供的函数实际上是
random.Random类的隐藏实例的绑定方法.
Run Code Online (Sandbox Code Playgroud)def choice(self, seq): """Choose a random element from a non-empty sequence.""" try: i = self._randbelow(len(seq)) except ValueError: raise IndexError('Cannot choose from an empty sequence') from None return seq[i]