Ays*_*thy 2 python list python-2.7
我有一个功能来检查列表中的"负","正"和"零"值.以下是我的功能:
def posnegzero(nulist):
for x in nulist:
if x > 0:
return "positive"
elif x < 0:
return "negative"
else:
return "zero"
Run Code Online (Sandbox Code Playgroud)
但是当我运行此函数时,它会在检查列表中第一个数字的值后停止.例如:
>>> posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
"negative"
Run Code Online (Sandbox Code Playgroud)
我希望它继续整个列表.在上面的函数中,如果我改变了returnto的每个实例print,那么它会做它应该做的事情,但是现在我不希望它None在函数完成时说出来.我错在哪里的想法?
Moi*_*dri 12
return停止函数的控制流并返回流.您可以yield在这里使用将您的功能转换为生成器.例如:
def posnegzero(nulist):
for x in nulist:
if x > 0:
yield "positive"
elif x < 0:
yield "negative"
else:
yield "zero"
Run Code Online (Sandbox Code Playgroud)
每次next()在返回的对象上调用时,它将产生下一个结果:
>>> result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
>>> next(result)
'negative'
>>> next(result)
'positive'
>>> next(result)
'positive'
Run Code Online (Sandbox Code Playgroud)
或者您可以立即获得所有结果:
>>> result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
>>> list(result)
['negative', 'positive', 'positive', 'negative', 'negative', 'zero', 'positive', 'negative']
Run Code Online (Sandbox Code Playgroud)
您也可以使用for循环迭代它.for循环重复调用该next()方法,直到它收到StopIteration异常.例如:
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
Run Code Online (Sandbox Code Playgroud)
有关更多信息yield,请参阅:"yield"关键字有什么作用?
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |