2014-10-18 174 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' 

重命名該腳本以免掩蓋它。