2014-10-18 177 views
0

我想使用对开模块,但是当我尝试import bisect我得到这个错误 :的Python 3.4 - 无法导入模块

NameError: global name 'bisect_left' is not defined 

而这个错误,当我尝试from bisect import bisect_left

ImportError: cannot import name bisect_left 

我试图从python文档中使用这个函数:

def index(a, x): 
    'Locate the leftmost value exactly equal to x' 
    i = bisect_left(a, x) 
    if i != len(a) and a[i] == x: 
     return i 
    else: 
     return False 

我在做什么错?

+1

无法复制 - 在OS X的'3.4.0'中对我很好。您能否提供有关您的安装的更多信息? – jonrsharpe 2014-10-18 20:24:56

+0

我有最新的python 3版本 - 3.4.2从python.org。 – kaloyan1123 2014-10-18 20:30:05

+1

@jonrsharpe:我可以很好地复制它。 OP命名他们的脚本'bisect.py'。 – 2014-10-18 20:33:33

回答

1

您将您的脚本命名为bisect.py;它正在导入,而不是标准库:

nidhogg:stackoverflow-3.4 mj$ cat bisect.py 
import bisect 

bisect.bisect_left 
nidhogg:stackoverflow-3.4 mj$ bin/python bisect.py 
Traceback (most recent call last): 
    File "bisect.py", line 1, in <module> 
    import bisect 
    File "/Users/mj/Development/venvs/stackoverflow-3.4/bisect.py", line 3, in <module> 
    bisect.bisect_left 
AttributeError: 'module' object has no attribute 'bisect_left' 
nidhogg:stackoverflow-3.4 mj$ echo 'from bisect import bisect_left' > bisect.py 
nidhogg:stackoverflow-3.4 mj$ bin/python bisect.py 
Traceback (most recent call last): 
    File "bisect.py", line 1, in <module> 
    from bisect import bisect_left 
    File "/Users/mj/Development/venvs/stackoverflow-3.4/bisect.py", line 1, in <module> 
    from bisect import bisect_left 
ImportError: cannot import name 'bisect_left' 

重命名该脚本以免掩盖它。