英文:
Return several values inside for loop
问题
我有一个必须使用for循环返回多个值的函数。我不希望将这些值存储在列表或字典中。由于使用return
,我只得到第一个值。如何连续返回所有值?我尝试使用生成器和yield
,但不确定如何使用它。
以下是该函数:
import random
def my_function():
for i in range(3):
return(dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0)
生成器和使用yield
适用于我的需求吗?
英文:
I have a function that must return several values using a for loop. I do not wish to store the values inside a list or a dict. Because of the use of the return
, I only get the first value. How can I return all values successively? I tried using generators and yield
but I'm not sure how to use it.
here is the function:
import random
def my_function():
for i in range(3):
return(dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0)
Are generators and the use of yield
suited for my need?
答案1
得分: 1
将`return`替换为`yield`以创建一个生成器:
```python
import random
def my_function():
for i in range(3):
yield dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0
g = my_function()
for d in g:
print(d)
输出:
({'x': [[0]], 'y': [[10]]}, 0)
({'x': [[0]], 'y': [[1]]}, 0)
({'x': [[3]], 'y': [[0]]}, 0)
您还可以使用next
手动消耗下一个值:
g = my_function()
print(next(g))
print(next(g))
print(next(g))
print(next(g)) # 会引发 StopIteration 异常
输出:
({'x': [[4]], 'y': [[4]]}, 0)
({'x': [[4]], 'y': [[9]]}, 0)
({'x': [[7]], 'y': [[2]]}, 0)
...
StopIteration:
英文:
Replace return
by yield
to create a generator:
import random
def my_function():
for i in range(3):
yield dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0
g = my_function()
for d in g:
print(d)
Output:
({'x': [[0]], 'y': [[10]]}, 0)
({'x': [[0]], 'y': [[1]]}, 0)
({'x': [[3]], 'y': [[0]]}, 0)
You can also use next
to consume manually the next value:
g = my_function()
print(next(g))
print(next(g))
print(next(g))
print(next(g)) # Will raise a StopIteration exception
Output:
({'x': [[4]], 'y': [[4]]}, 0)
({'x': [[4]], 'y': [[9]]}, 0)
({'x': [[7]], 'y': [[2]]}, 0)
...
StopIteration:
答案2
得分: 1
我希望这能让你更好地理解。接下来,逐个为你提供值,如果你想获取所有的值,请将你的函数包装在一个列表内。
import random
def my_function():
for i in range(3):
yield(dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0)
a = my_function()
print(next(a)) # 逐个获取
print(next(a))
print(list(my_function())) # 获取所有值
英文:
I hope, this gives you better understanding. next gives you value one by one and if you want all values wrap your function inside a list
import random
def my_function():
for i in range(3):
yield(dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0)
a = my_function()
print(next(a)) # one by one
print(next(a))
print(list(my_function())) # get all values
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论