9

我正在尝试import random在 python 中使用该语句,但它似乎没有任何方法可以使用。

我错过了什么吗?

4

8 回答 8

36

您的工作目录中可能有一个名为 random.py 或 random.pyc 的文件。这掩盖了内置的随机模块。您需要将 random.py 重命名为 my_random.py 和/或删除 random.pyc 文件。

要确定发生了什么,请执行以下操作:

>>> import random
>>> print random.__file__

这将准确显示正在导入的文件。

于 2008-09-16T18:26:02.610 回答
3

发生这种情况是因为您在 python 搜索路径中有一个 random.py 文件,很可能是当前目录。

Python 正在使用 sys.path 搜索模块,该路径通常包括标准站点包之前的当前目录,其中包含预期的 random.py。

This is expected to be fixed in Python 3.0, so that you can't import modules from the current directory without using a special import syntax.

Just remove the random.py + random.pyc in the directory you're running python from and it'll work fine.

于 2008-09-16T23:22:30.993 回答
2

我认为您需要提供更多信息。根据问题中的信息,实际上不可能回答为什么它不起作用。random 的基本文档位于: https ://docs.python.org/library/random.html

你可以在那里检查。

于 2008-09-16T16:51:27.873 回答
1
Python 2.5.2 (r252:60911, Jun 16 2008, 18:27:58)
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.seed()
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> random.randint(0,3)
3
>>> random.randint(0,3)
1
>>>  
于 2008-09-16T16:53:00.570 回答
1

如果您尝试运行的脚本本身名为 random.py,那么您将遇到命名冲突。为您的脚本选择一个不同的名称。

于 2008-09-16T20:11:09.843 回答
0

你能发布一个你想要做什么的例子吗?从您的问题中不清楚实际问题是什么。

以下是如何使用随机模块的示例:

import random
print random.randint(0,10)
于 2008-09-16T16:52:11.273 回答
0

似乎对我来说工作得很好。查看官方python文档中的随机方法:

>>> import random
>>> random.random()
0.69130806168332215
>>> random.uniform(1, 10)
8.8384170917436293
>>> random.randint(1, 10)
4
于 2008-09-16T16:53:43.000 回答
0

为我工作:

Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) 
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> brothers = ['larry', 'curly', 'moe']
>>> random.choice(brothers)
'moe'
>>> random.choice(brothers)
'curly'
于 2008-09-16T18:19:19.740 回答