我有一个函数来检查列表中的"负"、"正"和"零"值。以下是我的函数:
def posnegzero(nulist):
for x in nulist:
if x > 0:
return "positive"
elif x < 0:
return "negative"
else:
return "zero"
但是当我运行这个函数时,它会在检查列表中第一个数字的值后停止。例如:
>>> posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
"negative"
我希望它继续整个列表。在上面的函数中,如果我将 return
的每个实例都更改为 print
,那么它会做它应该做的,但现在我不希望它在函数完成时说None
。知道我哪里出错了吗?
return
停止函数的控制流并返回流。您可以在此处使用yield
,它将函数转换为生成器。例如:
def posnegzero(nulist):
for x in nulist:
if x > 0:
yield "positive"
elif x < 0:
yield "negative"
else:
yield "zero"
每次在返回的对象上调用 next()
时,它都会产生下一个结果:
>>> result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
>>> next(result)
'negative'
>>> next(result)
'positive'
>>> next(result)
'positive'
或者,您可以一次获得所有结果,如下所示:
>>> result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
>>> list(result)
['negative', 'positive', 'positive', 'negative', 'negative', 'zero', 'positive', 'negative']
您还可以使用循环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
有关yield
的更多信息,请参阅:">yield"关键字有什么作用?
您的问题立即在第一个列表元素上返回
就个人而言,我会这样做 - 仅为值定义函数。不是列表。对列表的每个值运行函数
(蟒蛇 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
其工作原理如下:
>>> posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
['negative', 'positive', 'positive', 'negative', 'negative', 'zero', 'positive', 'negative']
甚至使用条件列表理解:
def posnegzero(lst):
return ["positive" if x > 0 else "negative" if x < 0 else "zero" for x in lst]
试试这个
d=["pos" if i>0 else "neg"if i<0 else "zero" for i in [-20, 1, 2, -3, -5, 0, 100, -123]]
输出
['负', 'pos', 'pos', 'neg', 'neg', 'zero', 'pos', 'neg']