简体   繁体   English

返回函数如何在循环和过程中工作?

[英]How does the return function work within a loop and procedure?

I thought a for-loop would run through all the elements in a list regardless of the conditions of the loop. 我认为无论循环的条件如何,for循环都会遍历列表中的所有元素。
For the problem below-I would expect the printed output to be 6,-1, 对于以下问题-我希望打印输出为6,-1,
the last position where p[count]==n and then my return statement after the loop ends. 最后一个位置,其中p[count]==n ,然后是循环结束后的return语句。

When if p[count]==n finds a match, does the loop and procedure keep running past my return function? if p[count]==n找到匹配项,则循环和过程是否继续运行超过我的返回函数?
Does someone have a good explanation of how this works? 有人对此工作原理有很好的解释吗?

def find_element(p,n):
    count=0
    for x in p:
        if p[count]==n:
            return count
        count=count+1
    return '-1'

print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')

When executing a function the first return statement encountered will end the function, and the result of the expression given to the return statement will be given back to the caller. 当执行一个函数时,遇到的第一个return语句将终止该函数,并且将给return语句的表达式结果返回给调用者。 In this case, when p[count] == n is True , the count will be returned. 在这种情况下,当p[count] == nTrue ,将返回计数。 The function will only return -1 if the for x in p: loop is exhausted without ever finding the appropriate element. 如果for x in p:循环中的for x in p:耗尽,而找不到合适的元素,则该函数仅返回-1。

All that being said however the loop you have doesn't quite behave the way the function suggests it should.. If you are hoping to find the list of every index which has the value n you will want something like this: 不管怎么说,您所拥有的循环并没有完全按照函数建议的方式运行。.如果您希望找到具有值n的每个索引的列表,您将需要这样的东西:

def find_element(p,n):
    return [i for i,x in enumerate(p) if x == n]

print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')
#[1, 3, 4, 6]

Functions can only call return one time. 函数只能调用return一次。 As pointed out in the comments this returns from the function to the caller. 如注释中所指出的,这将从函数返回到调用者。 Thus the rest of the code does not run. 因此,其余代码不会运行。

If you want to return all of the relevant indices you can either: 如果要返回所有相关索引,则可以:

  1. Keep track of the indices in a list and just return the list at the end of the function 跟踪列表中的索引,然后在函数末尾返回列表

  2. Look into generators and use the yield keyword 查看生成器并使用yield关键字

Say you typically run 10 laps around a track after work but your boss calls you after the 4th lap and says "we have an emergency and need you to return to work right away" then the imperative to return will override the imperative to complete the laps (at least if you want to be a good employee). 假设您下班后通常在赛道上跑10圈,但老板在第4圈后打电话给您,并说“我们有紧急情况,需要您立即返回工作状态”,那么当务之急是要超越要务来完成每一圈(至少如果您想成为一名好员工)。 Return -- not the if statement per se -- is what caused your loop to end. Return-不是if语句本身-是导致循环结束的原因。

Your first question: "When if p[count] == n finds a match, does the loop and procedure stop running?" 您的第一个问题:“ if p[count] == n找到匹配项,则循环和过程是否停止运行?”

The answer is no. 答案是不。 The program exits the find_element function when it hits any return statement. 程序在遇到任何return语句时退出find_element函数。 In your case, either return count , or return -1 . 在您的情况下,要么return count ,要么return -1

What you are concerned about is called "Flow Control". 您所关心的称为“流控制”。

For loops are a form of flow control that give you the ability to do repetition. For循环是一种流控制形式,可让您进行重复。 If/(then)/Else is another form to do decisions. If /(then)/ Else是进行决策的另一种形式。

The python docs (chapter 4) have a good introduction to this. python文档(第4章)对此做了很好的介绍。

These statements can break out of a loop: 这些语句可以打破循环:

  1. The return statement. return语句。
  2. The break statement. break语句。

At run-time, the loop can also be broken if an unhandled exception occurs within it. 在运行时,如果其中发生未处理的异常,则循环也可能被破坏。

A related flow is implemented using the continue statement. 使用continue语句实现相关流程。 If you are part-way into an iteration of the loop, continue will skip the rest of the iteration and proceed to the next one. 如果你是兼职的方式进入循环迭代, continue将跳过迭代的其余部分,并继续下一个。

In your particular example, the if statement occurs within the context of a loop which is within the context of a function. 在您的特定示例中, if语句出现在函数上下文内的循环上下文内。 The return statement takes us not only out of the loop, but out of the function and sets the value returned by the function. return语句不仅使我们脱离循环,而且使我们脱离函数,并设置函数返回的值。

The return aborts all further activities within the function and returns control to the caller. 返回中止函数内的所有其他活动,并将控制权返回给调用方。 (as juanchopanza said) (如juanchopanza所说)

Incidentally, you don't need to keep two separate variable count and x . 顺便说一句,您不需要保留两个单独的变量countx They are redundant. 它们是多余的。 Do this instead: 改为这样做:

def find_element(p,n):
    try:
        return p.index(n)
    except ValueError:
        return -1

It works: 有用:

>>> print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')
1
>>> print find_element(['1', '2', '1', '2', '2', '1', '2'],'4')
-1

What your for loop is trying to do is check if p[count] is equal to n and if so, stops and exit the loop and your function ends and returns the current value of count . 您的for循环尝试执行的操作是检查p[count]是否等于n ,如果是,则停止并退出循环,函数结束并返回count的当前值。 But if it doesn't find a match, the loop exits anyway and your function will return -1 . 但是,如果找不到匹配项,则循环将退出,并且您的函数将返回-1

Also, you could/should use count += 1 to increment count. 另外,您可以/应该使用count += 1来增加count。

In Python, as is all (most) languages, a return does return (sic) the value AND terminate the function (or procedure, as is it called in the question; but function, or calleble is more correct). 在Python中,就像所有(大多数)语言一样,return确实返回值(sic)并终止函数(或过程,如在问题中所称;但是函数或calleble更为正确)。

Python does however, has an option to separate them. 但是,Python确实可以选择它们分开 By using ' yield ': that will return the value, but (kind of) continues the loop. 通过使用' yield ':将返回值,但是(某种)继续循环。 Note: the function (or generator/iterator) has to be called in a loop, to return (yield) each value, one by one. 注意:必须在循环中调用函数(或生成器/迭代器),以逐个返回(屈服)每个值。

This is a bit advanced, so I leave it to the reader to lookup the documentation and good examples 这有点高级,因此我留给读者查找文档和好的示例

Last remark: using a count er, as shown is not pythonic ! 最后一句话:使用计数呃,如不符合Python! Use enumerate helper instead. 请改用枚举助手。

def find_element(p,n):
    for count, elm in enumerate(p):  # p is a list or sequence 
        if elm == n                       # maybe 'is' is better as '=='
            return count
    return -1                               # however, returning None is  more Pythonic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM