random.choice() 需要两个参数? [英] random.choice() takes two arguments?
问题描述
我在以下掷骰函数中犯了一个简单的错误:
随机导入def rollDie():返回 random.choice(1,2,3,4,5,6)打印(rollDie())
我知道我需要将序列作为列表或元组传递,但我对以下错误消息更好奇.
回溯(最近一次调用最后一次):文件Lecture 5.2 -- stochastic - die roll example.py",第 8 行,在 <module> 中.打印(rollDie())文件Lecture 5.2 -- stochastic - die roll example.py",第 6 行,在 rollDie返回 random.choice(1,2,3,4,5,6)类型错误:choice() 需要 2 个位置参数,但给出了 7 个
消息说choice() 需要 2 个位置参数,但给出了 7 个".
但是文档只说明了一个参数(序列).https://docs.python.org/3/library/random.html
第二个参数是什么(在我的例子中是第七个参数)?这是种子吗(我没有指定,所以正在由时钟初始化)?
choice()
是隐藏的 Random()
实例 random
模块维护.因为它是一个方法,所以它有 2 个参数:self
和可从中做出选择的迭代.
来自模块文档:
<块引用>该模块提供的函数实际上是 random.Random
类的隐藏实例的绑定方法.
def 选择(自我,序列):"""从非空序列中随机选择一个元素."""尝试:i = self._randbelow(len(seq))除了值错误:从无引发 IndexError('不能从空序列中选择')返回序列[i]
I made a simple mistake in the following die roll function:
import random
def rollDie():
return random.choice(1,2,3,4,5,6)
print(rollDie())
I do know that I need to pass the sequence as a list or tuple, but I was more curious about the following error message.
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
The message says "choice() takes 2 positional arguments but 7 were given".
But the documentation indicates only one argument (sequence). https://docs.python.org/3/library/random.html
What is the second argument (or seventh in my case)? Is this the seed (which I have not specified so is being initialised by the clock)?
choice()
is a method on the hidden Random()
instance the random
module maintains. Because it is a method, it has 2 arguments: self
and the iterable from which to make a choice.
From the module documentation:
The functions supplied by this module are actually bound methods of a hidden instance of the
random.Random
class.
and the random
module source code:
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]
这篇关于random.choice() 需要两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!