我在下面的掷骰子函数中犯了一个简单的错误:
import random
def rollDie():
return random.choice(1,2,3,4,5,6)
print(rollDie())
我知道我需要将序列作为列表或元组传递,但我对以下错误消息更好奇。
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
消息说“choice() 接受 2 个位置参数,但给出了 7 个”。
但文档仅指示一个参数(序列)。 https://docs.python.org/3/library/random.html
第二个参数是什么(在我的例子中是第七个)?这是种子吗(我没有指定,所以由时钟初始化)?
请您参考如下方法:
choice() 是 random 模块维护的隐藏 Random() 实例上的一个方法。因为它是一个方法,所以它有 2 个参数:self 和要从中做出选择的 iterable。
The functions supplied by this module are actually bound methods of a hidden instance of the
random.Randomclass.
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]
