[英]'module' object has no attribute 'choice' - trying to use random.choice
Could someone please tell me what I may be doing wrong.有人可以告诉我我可能做错了什么。 I keep getting this message when I run my python code:
运行 python 代码时,我不断收到此消息:
import random
foo = ['a', 'b', 'c', 'd', 'e']
random_item = random.choice(foo)
print random_item
Error错误
AttributeError: 'module' object has no attribute 'choice'
AttributeError:“模块”对象没有属性“选择”
Shot in the dark: You probably named your script random.py
. 在黑暗中拍摄:您可能将脚本命名为
random.py
。 Do not name your script the same name as the module. 不要将脚本命名为与模块相同的名称。
I say this because the random
module indeed has a choice
method, so the import is probably grabbing the wrong (read: undesired) module. 我这样说是因为
random
模块确实有一个choice
方法,所以导入可能会抓错(读取:不需要的)模块。
for me the problem is I use 对我来说问题是我用的
random.choices
in python 3.6 local dev but the server is python3.5 don't have this method... 在python 3.6本地开发但服务器是python3.5没有这个方法...
Sounds like an import issue. 听起来像是一个导入问题。 Is there another module in the same directory named
random
? 在同一目录中是否有另一个名为
random
模块? If so (and if you're on python2, which is obvious from print random_item
) then it's importing that instead. 如果是这样(如果您使用的是python2,这在
print random_item
是显而易见的)那么它将导入它。 Try not to shadow built-in names. 尽量不要隐藏内置名称。
You can test this with the following code: 您可以使用以下代码对此进行测试:
import random
print random.__file__
The actual random.py
module from stdlib lives in path/to/python/lib/random.py
. stdlib中的实际
random.py
模块位于path/to/python/lib/random.py
。 If yours is somewhere else, this will tell you where it is. 如果你的是其他地方,这将告诉你它在哪里。
In short, Python's looking in the first file it finds named "random", and isn't finding the choice attribute. 简而言之,Python查找它发现的名为“random”的第一个文件,并且没有找到choice属性。
99.99% of the time, that means you've got a file in the path/directory that's already named "random". 99.99%的时间,这意味着你已经在路径/目录中有一个已经命名为“随机”的文件。 If that's true, rename it and try again.
如果这是真的,重命名并重试。 It should work.
它应该工作。
I also got this error by naming a method random
like this: 通过像这样
random
命名方法我也得到了这个错误:
import random
def random():
foo = ['a', 'b', 'c', 'd', 'e']
random_item = random.choice(foo)
print random_item
random()
It's not your case (naming a file random.py
) but for others that search about this error and may make this mistake. 这不是你的情况(命名文件
random.py
),但对于其他搜索此错误的人可能会犯这个错误。
If you are using Python older than 3.6 version, than you have to use NumPy library to achieve weighted random numbers.如果您使用的 Python 版本低于 3.6,则必须使用 NumPy 库来实现加权随机数。 With the help of choice() method, we can get the random samples of one dimensional array and return the random samples of numpy array.
借助choice()方法,我们可以获得一维数组的随机样本,并返回numpy数组的随机样本。
from numpy.random import choice
sampleList = [100, 200, 300, 400, 500]
randomNumberList = choice(
sampleList, 5, p=[0.05, 0.1, 0.15, 0.20, 0.5])
print(randomNumberList)
source: geeksforgeek来源: geeksforgeek
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.