2008-09-16 67 views

回答

34

你可能在你的工作目录中的文件名为random.py或random.pyc。这隐藏了内置的随机模块。您需要将random.py重命名为像my_random.py和/或删除random.pyc文件。

说句肯定发生了什么事情,这样做:

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

会告诉你到底是哪文件被导入。

+0

在Python 3.3.2 shell中,我必须省略`print`来获取文件路径。 – Tony 2014-10-16 10:13:42

0

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

这里有一个如何使用随机模块的示例:

import random 
print random.randint(0,10) 
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 
>>> 
0

似乎为我工作的罚款。看看在official python documentation方法随机:

>>> import random 
>>> random.random() 
0.69130806168332215 
>>> random.uniform(1, 10) 
8.8384170917436293 
>>> random.randint(1, 10) 
4 
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' 
1

您可能运行的脚本名为random.py本身吗?

3

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

Python正在使用sys.path搜索模块,sys.path通常包含标准site-packages之前的当前目录,其中包含预期的random.py。

预计这将在Python 3.0中得到解决,以便您无需使用特殊导入语法即可从当前目录导入模块。

只需从您运行python的目录中删除random.py + random.pyc,它就可以正常工作。