Python 3.4 - 无法导入模块

kal*_*123 2 python importerror bisect python-3.x

我想使用 bisect 模块,但当我尝试执行以下操作时出现此错误import bisect

NameError: global name 'bisect_left' is not defined
Run Code Online (Sandbox Code Playgroud)

当我尝试时出现此错误from bisect import bisect_left

ImportError: cannot import name bisect_left
Run Code Online (Sandbox Code Playgroud)

我尝试使用 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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Mar*_*ers 7

您为脚本命名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'
Run Code Online (Sandbox Code Playgroud)

重命名脚本以免掩盖它。