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
就像返回一样,我可以使用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