我有一个函数来检查列表中的“负”、“正”和“零”值。以下是我的职能:
def posnegzero(nulist):
for x in nulist:
if x > 0:
return "positive"
elif x < 0:
return "negative"
else:
return "zero"
但当我运行这个函数时,它会在检查列表中第一个数字的值后停止。例如:
^{pr2}$
我想在整个名单上继续。如果这个函数在cd3>中完成,那么它现在应该做什么。你知道我哪里出错了吗?在
Tags:
您的问题在第一个列表元素上立即返回
就个人而言,我会这样做-只为值定义函数。不是单子。在列表的每个值上运行函数
(Python 3)
您可以将结果生成一个列表:
其工作原理如下:
^{pr2}$甚至是有条件的列表理解:
^{} 停止函数的控制流并返回流。您可以在这里使用^{} ,它将把您的函数转换成generator。例如:
每次对返回的对象调用^{} 时,它将生成下一个结果:
^{pr2}$或者您可以同时获得所有结果:
您也可以使用} 方法,直到收到^{} 异常。例如:
for
循环来迭代它。for
循环反复调用^{有关
yield
的详细信息,请参阅:What does the “yield” keyword do?相关问题 更多 >
编程相关推荐