gpt4 book ai didi

python - 有没有可能像return一样一次yield两个东西?

转载 作者:太空狗 更新时间:2023-10-30 00:49:48 26 4
gpt4 key购买 nike

def foo(choice):
for i in limit:
d1 = doSomeCalc()
d2 = doSomeOtherCalc()
if choice == "stuff":
yield {
d1 : "value"
}
else:
yield {
d2 : "Othervalue"
}

我有一个函数可以根据用户的选择产生两种类型的字典

def bar():
for i in limit:
d1 = doSomeCalc()
d2 = doSomeOtherCalc()
return {d1 : "value"}, {d2 : "Othervalue"}

a,b = bar() // when function returns two dictionaries

就像 return 一样,我可以使用 yield 一次给出两个不同的字典吗?我将如何获得每个值?

我现在不想在我的函数中保留 if-else

最佳答案

您一次只能产生一个值。迭代生成器将依次产生每个值。

def foo():
yield 1
yield 2

for i in foo():
print i

和往常一样,该值可以是一个元组。

def foo():
yield 1, 2

for i in foo():
print i

关于python - 有没有可能像return一样一次yield两个东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28205509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com