Python 如何在不中断循环的情况下返回值?
我想知道如何在不中断Python循环的情况下返回值 这里有一个例子:Python 如何在不中断循环的情况下返回值?,python,function,return-value,Python,Function,Return Value,我想知道如何在不中断Python循环的情况下返回值 这里有一个例子: def myfunction(): list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(list) total = 0 for i in list: if total < 6: return i #get first element then it breaks total +=
def myfunction():
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(list)
total = 0
for i in list:
if total < 6:
return i #get first element then it breaks
total += 1
else:
break
myfunction()
def myfunction():
列表=['a','b','c','d','e','f','g']
打印(列表)
总数=0
对于列表中的i:
如果总数小于6:
return i#获取第一个元素,然后它将中断
总数+=1
其他:
打破
myfunction()
return
将只得到第一个答案,然后离开循环,我不希望这样,我希望返回多个元素,直到循环结束
如何解决这个问题,有什么解决方案吗?您可以为此创建一个函数,这样您就可以从生成器中产生值(使用产生语句后,您的函数将成为生成器)
请参阅以下主题,以更好地了解如何使用它:
使用生成器的示例如下:
def simple_generator(n):
i = 0
while i < n:
yield i
i += 1
my_simple_gen = simple_generator(3) // Create a generator
first_return = my_simple_gen.next() // 0
second_return = my_simple_gen.next() // 1
注意:在使用列表的方法中,您必须知道您的函数将在结果
列表中返回多少值,以避免太多值无法解包
错误使用
def myfunction():
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
total = 0
for i in l:
if total < 6:
yield i #yields an item and saves function state
total += 1
else:
break
g = myfunction()
或者,在for循环中,执行以下操作:
>>> for returned_val in myfunction():
... print(returned_val)
a
b
c
d
e
f
使用列表切片最容易表达您的需求:
>>> l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> l[:6]
# ['a', 'b', 'c', 'd', 'e', 'f']
或者创建另一个列表,您将在函数末尾返回该列表
def myfunction():
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
ret = []
total = 0
for i in l:
if total < 6:
total += 1
ret.append(i)
return ret
myfunction()
# ['a', 'b', 'c', 'd', 'e', 'f']
def myfunction():
l=['a','b','c','d','e','f','g','h','i']
ret=[]
总数=0
对于l中的i:
如果总数小于6:
总数+=1
ret.append(i)
回程网
myfunction()
#['a','b','c','d','e','f']
Ayield
创建生成器的语句就是您想要的
然后使用下一个方法获取循环返回的每个值
var = my_func().next()
您可以将其分配给一个全局/类变量,但若不中断循环就无法返回,据我所知,这似乎是一种非常复杂的方法,可以做一些非常简单的事情。你能解释一下你的代码的目的吗?myfunction
的目的是什么?@DeliriousSyntax是的,我知道,但我想知道是否有一些方法可以避免that@Gabriel这只是一个例子,真正的代码是Django,太长了,所以我没有发布它,但是你应该知道的是,我需要返回很多特定数量的值,所以不应该忽略total+=1
。我想Jim的答案就是你需要的。是的,这正是我要搜索的。这个问题有点超出了我的要求,但是我应该在myfunction()中调用returned\val的位置:
在Django、模板或模型中?需要时调用它;我真的不知道你的设置/你想达到什么目的才能告诉你更多。回答得好。实际值将是产生的
,而不是返回的
def myfunction():
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
ret = []
total = 0
for i in l:
if total < 6:
total += 1
ret.append(i)
return ret
myfunction()
# ['a', 'b', 'c', 'd', 'e', 'f']
var = my_func().next()