本文介绍了防止功能在"for"循环内的第一次“返回"时不停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有检查列表中负",正"和零"值的功能.下面是我的功能:

I have a function to check for the "negative", "positive" and "zero" value in the list. Below is my function:

def posnegzero(nulist):
    for x in nulist:
        if x > 0:
            return "positive"
        elif x < 0:
            return "negative"
        else:
            return "zero"

但是当我运行此函数时,它会在检查列表中第一个数字的值后停止.例如:

But when I run this function, it stops after checking the value of the first number in the list. For example:

>>> posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
"negative"

我希望它继续显示整个列表.在上面的函数中,如果我将return的每个实例都更改为print,那么它会执行应做的事情,但是现在我不希望它在函数完成时说None.关于我哪里出了错的任何想法?

I want it to continue for the entire list. In the above function, if I change every instance of return to print, then it does what it should but now I don't want it to say None when the function is complete. Any ideas of where I went wrong?

推荐答案

return 停止函数的控制流程并返回该流程.您可以在此处使用 yield 将函数转换为 生成器 .例如:

return stops the control flow of your function and returns back the flow. You may use yield here which will convert your function into a generator. For example:

def posnegzero(nulist):
    for x in nulist:
        if x > 0:
            yield "positive"
        elif x < 0:
            yield "negative"
        else:
            yield "zero"

每次 next() 都会产生下一个结果在返回的对象上被调用:

It will yield the next result every time next() is called on the returned object:

>>> result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
>>> next(result)
'negative'
>>> next(result)
'positive'
>>> next(result)
'positive'

或者您可以一次获得所有结果:

Or you may get all the result at once as:

>>> result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
>>> list(result)
['negative', 'positive', 'positive', 'negative', 'negative', 'zero', 'positive', 'negative']

您还可以使用for循环对其进行迭代. for循环重复调用 next() 方法,直到它收到 StopIteration 异常.例如:

You can also iterate it using for loop. for loop repeatedly calls the next() method until it receives a StopIteration exception. For example:

for result in posnegzero([-20, 1, 2, -3, -5, 0, 100, -123]):
    print(result)

# which will print
negative
positive
positive
negative
negative
zero
positive
negative

有关yield的更多信息,请参阅: "yield"关键字的作用是什么?

For more information on yield, please refer: What does the "yield" keyword do?

这篇关于防止功能在"for"循环内的第一次“返回"时不停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:21