我正在使用python3。 首先我在終端中使用random.choice,它工作。AttributeError:'模塊'對象沒有'選擇'屬性
Python 3.2.3 (default, Feb 27 2014, 21:31:18)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> x = [1, 2, 3]
>>> random.choice(x)
3
但是,當我在我的腳本運行它,我得到的消息:
AttributeError: 'module' object has no attribute 'choice'
下面是代碼
import random
from scipy import *
from numpy import linalg as LA
import pickle
import operator
def new_pagerank_step(current_page, N, d, links):
print(links[current_page])
if random.rand() > 1 - d:
next_page = random.choice(links[current_page])
else:
next_page = random.randint(0, N)
return next_page
def pagerank_wikipedia_demo():
with open("wikilinks.pickle", "rb") as f:
titles, links = pickle.load(f)
current_page = 0
T = 1000
N = len(titles)
d = 0.4
Result = {}
result = []
for i in range(T):
result.append(current_page)
current_page = new_pagerank_step(current_page, N, d, links)
for i in range(N):
result.count(i)
Result[i] = result.count(i)/T
Sorted_Result = sorted(Result.items(), key=operator.itemgetter(1))
pagerank_wikipedia_demo()
這裏,links[i]
(i
爲整數)是名單。當我運行這個腳本時,它會失敗並顯示上面提到的信息。
我也檢查過腳本的名稱不是random
。並且/usr/lib/python3.2/random.py
只有一個文件random.py
爲什麼會發生這種情況?
做'進口隨機的;打印(隨機.__文件__)'在你的文件的頂部,你可能有一個文件random.py在你的路徑或.pyc文件 –
看到這個問題: 的http://計算器.com/questions/25695412/module-object-has-no-attribute-choice-trying-to-use-random-choice – RafaelC
我檢查過並且有兩個文件。一個是random.cpython-32.pyc,一個是random.py – epx