“内置函数”或“方法”对象不是subscriptab

2024-04-19 07:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

def binary_search(li, targetValue):
    low, high = 0, len[li] #error on this line
    while low <= high:
        mid = (high - low)/2
        if li[mid] == targetValue:
             return "we found it!"
        elif li[mid] > targetValue:
             low = mid - 1;
        elif li[mid] < targetValue:
             high = mid + 1;
    print "search failure "

最近刚刚发布了这个问题,但是我的代码仍然不起作用?


Tags: searchlenondeflineerrorlithis
3条回答

len是一个内置函数,但您试图将其用作序列:

len[li]

改为调用函数:

len(li)

注意这里的形状变化,索引是用方括号完成的,调用是用圆括号完成的。

Python使用(...)调用函数,使用[...]索引集合。此外,您现在要做的是索引内置函数len

要解决此问题,请使用括号而不是方括号:

low, high = 0, len(li)

您使用了错误的括号len(li)而不是len[li]

记住,当您试图访问一个函数时,如果您使用function(args),则需要使用[],实际上您正在访问一个序列,如列表。your_list[index]。len是一个内置函数,因此需要()

相关问题 更多 >