【发布时间】:2015-04-12 09:28:31
【问题描述】:
我正在使用 python3。 首先我在终端中使用 random.choice,它可以工作。
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的文件
为什么会这样?
【问题讨论】:
-
在文件顶部执行
import random;print(random.__file__),您的路径中可能有一个文件 random.py 或一个 .pyc -
我已经检查过了,有两个文件。一个是 random.cpython-32.pyc,一个是 random.py
-
@epx: 那就是完整路径?
-
@MartijnPieters:我不明白什么是完整路径。这是我在终端 Python 3.2.3 中看到的(默认,2014 年 2 月 27 日,21:31:18)[GCC 4.6.3] on linux2 键入“帮助”、“版权”、“信用”或“许可证”以获取更多信息信息。 >>> 导入随机数 >>> 打印 (random.__file__) /usr/lib/python3.2/random.py >>>
标签: python python-3.x random