防止函数在“for”循环中第一次不停止“return”

2024-10-04 03:24:09 发布

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

我有一个函数来检查列表中的“负”、“正”和“零”值。以下是我的职能:

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

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

^{pr2}$

我想在整个名单上继续。如果这个函数在cd3>中完成,那么它现在应该做什么。你知道我哪里出错了吗?在


Tags: 函数in列表forreturnifdefelse
3条回答

您的问题在第一个列表元素上立即返回

就个人而言,我会这样做-只为值定义函数。不是单子。在列表的每个值上运行函数

(Python 3)

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

print(list(map(posnegzero, [-20, 1, 2, -3, -5, 0, 100, -123]))) 

您可以将结果生成一个列表:

def posnegzero(lst):
    result = []

    for x in lst:
        if x > 0:
            result.append("positive")
        elif x < 0:
            result.append("negative")
        else:
            result.append("zero")

    return result

其工作原理如下:

^{pr2}$

甚至是有条件的列表理解:

def posnegzero(lst):
    return ["positive" if x > 0 else "negative" if x < 0 else "zero" for x in lst]

^{}停止函数的控制流并返回流。您可以在这里使用^{},它将把您的函数转换成generator。例如:

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

每次对返回的对象调用^{}时,它将生成下一个结果:

^{pr2}$

或者您可以同时获得所有结果:

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

您也可以使用for循环来迭代它。for循环反复调用^{}方法,直到收到^{}异常。例如:

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的详细信息,请参阅:What does the “yield” keyword do?

相关问题 更多 >