查找列表的索引

时间:2016-12-09 22:36:53

标签: python list while-loop

我的函数给出错误(" IndexError:列表索引超出范围"),我不确定为什么,即使先把i = 0.我的代码是打印索引第一个元素等于目标值,如果它不等于列表中的任何内容,则index = -1。 (使用While循环)

功能

def yareyare(list_g, list_size, target):
found = False
i = 0
while i < list_size or not found:
    if target == list_g[i]:
        found = True
        result = i
    else:
        i += 1
if not found:
    result = -1
print("The index is {}".format(result))

主要

# Imports
from index import yareyare

# Inputs
list_g = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_size = len(list_g)
target = str(input("What is the target value(1-10): "))

#
yareyare(list_g, list_size, target)

3 个答案:

答案 0 :(得分:2)

代码中有两个简单的错误。

首先,while循环的布尔逻辑应该是and而不是or,因为它允许它永远循环,因为在找到目标之前找不到True。< / p>

其次,您需要将目标转换为int而不是str

之后它应该可以工作。

答案 1 :(得分:1)

while i < list_size or not found:是罪魁祸首。只要found为false,即使用完列表条目,循环也会继续。也就是说,整个代码看起来很笨拙; Python方法通常使用list.index,或者更详细,带有enumerate和else子句的for循环。

答案 2 :(得分:0)

此代码存在一些问题。我将尝试修改您的错误,同时尽可能少地更改原始代码。你正在做的一些事情我会提出建议,比如将列表长度作为参数传递,而不是使用len并使用while循环。

你的第一个问题是目标是一个字符串,而你比较它的目标是整数。这意味着:

target == list_g[i]

永远不会是真的。必须更改为:

int(target) == list_g[i]

你的第二个问题是你在i < list_sizefound为假时循环。找到匹配项后,您将found设置为false,但永远不会增加i。这意味着i将始终保持相同的值,因此它始终等于list_g[i],因此您永远不会增加它。由于i始终小于列表长度i < list_size or not found将始终为真,您将陷入无限循环。您应该将or更改为and

以下是修复程序的功能:

def yareyare(list_g, list_size, target):
    found = False
    i = 0
    while i < list_size and not found:
        if int(target) == list_g[i]:
            found = True
            result = i
        else:
            i += 1
        if not found:
            result = -1
        print("The index is {}".format(result))