我已经编辑了上一节,下面一行中的任何内容都已经回答并且现在已经过时了:
def foo():
x = dict()
i = 0
while i < 10:
x[i] = i*2
i + = 1
yield x[i]
如何在新函数中调用 x[i] 的特定实例?
def foo():
x = dict()
i = 0
while i < 10:
x[i] = i*2
i + = 1
return x[i]
我希望它返回 x[1],x[2],x[3]...x[10],但现在它只 返回最终变量。我想这样做的原因是因为 在我的实际代码中,我不知道循环会迭代多少次
def main():
variable = foo()
print variable
我只是用它来向自己证明它返回了一些值
最佳答案
为此,考虑使用 yield
表达式:
def foo():
x = dict()
i = 0
while i < 10:
x[i] = x*2
i += 1
yield x[i]
for i in foo():
print i
正如@Ismail 所说,应该是 i += 1
而不是 x += 1
此外,x*2
应该做什么?您是说 i*2
吗?
yield
表达式的使用示例
def next_one(i,n):
while i < n:
yield i
i += 1
>>> for i in next_one(1,10):
... print i
...
1
2
3
4
5
6
7
8
9
[问题更新答案]
您可以使用 next()
运算符执行如下操作:
def next_one(i,n):
while i < n:
yield i
i += 1
def main(variable):
print next(variable)
variable = next_one(1,10)
main(variable)
main(variable)
main(variable)
[OUTPUT]
1
2
3
关于python - 使用 dict() 在循环中返回多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23147361/