Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带列表的基本while循环_Python_List_While Loop - Fatal编程技术网

Python 带列表的基本while循环

Python 带列表的基本while循环,python,list,while-loop,Python,List,While Loop,我在编程课上遇到了一个问题,它问: 使用while循环,编写一个函数find_indexitems,target,返回列表项中第一次出现的目标的索引。如果目标不在列表中,则函数应返回-1。您的函数不能使用内置的list方法list.index 到目前为止,我已经: def find_index(items, target): """Returns the index of the first occurrence of the target in the l

我在编程课上遇到了一个问题,它问:

使用while循环,编写一个函数find_indexitems,target,返回列表项中第一次出现的目标的索引。如果目标不在列表中,则函数应返回-1。您的函数不能使用内置的list方法list.index

到目前为止,我已经:

def find_index(items, target):
    """Returns the index of the first occurrence of the target in the list"""
    i = 0 
    while i < len(nums):
        return (items[0])
    if target not in items:
        return items[-1]
解决方案:

def find_index(items, target):
    """Returns the index of the first occurrence of the target in the list"""
    i = 0 
    if target not in items:
        return -1
    while i < len(nums):
        if items[i] == target:
            return i
        i+=1

您的问题的答案很容易给出,但在此之前,请务必了解参数在函数中是如何工作的

定义我的功能foo: printfoo 嗨,我变了 返回foo 喂 printmy_函数foo,foo 基本上,您正在定义一个变量foo,并且在参数中,您给出了相同的名称。因此,当您更改函数内的变量时,它不会更改其范围外的变量

hello
("Hi, I'm changed", 'hello')
按照惯例,您在函数中将参数定义为item和target,但实际上您使用的是外部定义的变量nums

使用while循环查找索引 在继续处理问题之前,请注意以下事项:

while循环将继续,直到满足特定条件。因此,阻止while循环永远运行是您的职责。 函数在收到返回时停止执行。 因此,您必须修改while循环以检查每个元素是否等于target,或者只需:

而我认为这些项目: 如果项目[i]==目标: 返回i i+=1与i=i+1相同 这里您要查找的索引是第i个值。注意:在python中,索引从0开始

鉴于此,你应该能够完成你的家庭作业。为了方便起见,这里是完整的解决方案

def查找索引,目标: i=0 而我认为这些项目: 如果项目[i]==目标: 返回i i+=1增量i,因为它不是自动完成的 返回-1 nums=[10,20,30] i=查找索引,20 普林蒂 >> 1
这个功能离目标还差得远。return立即结束函数并始终无条件返回列表中的第一项。您的代码将进入while循环,然后立即返回items中的第一项。即使这个循环是固定的,如果它没有在列表中找到目标,那么它将返回列表中的最后一项,而不是像问题所问的那样返回-1。你应该返回索引,换句话说是i,而不是items[…]。您还需要在循环中的某个地方增加i。您还需要一个if items[i]==目标。您还希望引用lenitems,而不是lennums。仅用return items[i]替换return items[0]不会改变此处的行为。需要做的更改比这多得多。@deceze添加条件语句可以解决问题,我的答案已被编辑以表明这一点。这仍然不够。编写它,然后重试。not in命令将搜索项目中的元素x。这可能会给出一个正确的输出,但我不认为这是在while循环中使用不在条件检查的方式。是的,现在它可以工作了。虽然目标不在items检查是多余的,因为它会导致您在最后迭代列表两次。您只需要在while循环之后返回-1。
hello
("Hi, I'm changed", 'hello')
def find_index(items, target):
    i = 0
    while i < len(items):
        if items[i] == target:
            return i
        i += 1

    return -1


items = [10, 20, 30]
print(find_index(items, 0)) # for fail case, returns -1
print(find_index(items, 10)) # for successful case, returns 0 e.g.