1

我想使用 bisect 模块,但是当我尝试时出现此错误import bisect

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

我究竟做错了什么?

4

1 回答 1

5

你命名了你的脚本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'

重命名脚本以免掩盖它。

于 2014-10-18T20:30:16.753 回答