2008-09-16 65 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,它就可以正常工作。