是否可以将while循环中的变量存储到函数中,然后在循环结束时从函数中调用该变量
例如:在while循环期间,问题在于当我尝试从store()检索变量时它失败了...因为它需要传递参数.
def store(a,b,c):
x1 = a
y1 = b
z1 = c
return (x1,y1,z1)
def main():
while condition:
x = .......
y = .......
z = .......
......
......
store(x,y,z) #store to function...
......
......
......
s1,s2,s3 = store()
......
......
......
Run Code Online (Sandbox Code Playgroud)
小智 8
正如其他人所说,可能有一个比这更合适的选择,但在某些情况下(可能在REPL中)可能会很方便.这是一个简单的函数,可以使用任意数量的值执行您想要的操作.
def store(*values):
store.values = values or store.values
return store.values
store.values = ()
Run Code Online (Sandbox Code Playgroud)
>>> store(1, 2, 3)
>>> a, b, c = store()
>>> print a, b, c
1 2 3
>>> store(4, 5)
>>> a, b = store()
>>> print a, b
4 5
Run Code Online (Sandbox Code Playgroud)
嗯,除非我误解,这是一个非问题的经典非解决方案.
为什么不直接使用这种语言呢?
while condition:
x = something
y = else
z = altogether
...
save_state = (x,y,z) ## this is just a python tuple.
...
# do something else to x, y and z, I assume
...
x, y, z = save_state
Run Code Online (Sandbox Code Playgroud)
根据类型x,y并且z你可能要小心的存储copy到元组.
(另外,你的缩进是错误的,并且end在python中没有这样的东西.)
更新:好的,如果我理解得更好,问题就是能够在下次通过时使用之前的值.在最简单的情况下,根本没有问题:下一次循环,是,和的值x,它们是前一次通过循环结束的时间(这是所有编程语言的工作方式) .yz
但如果你想明确,请尝试这样的事情:
x_prev = some_starting_value
x = some_starting_value
while condition:
x = something_funky(x_prev)
.... other stuff ....
x_prev = x
Run Code Online (Sandbox Code Playgroud)
(但请再次注意,你根本不需要x_prev:x=something_funky(x)会工作.)
从技术上讲,如果您对使用函数执行此操作有强烈的渴望,则始终可以使用闭包(众所周知,这是一个穷人的对象)来完成:
def store(a,b,c):
def closure():
return (a,b,c)
return closure
stored = store(1,2,3)
print stored()
Run Code Online (Sandbox Code Playgroud)
打印在 (1,2,3)