python 是否具有“临时”或“非常本地”的变量功能?我正在寻找一个单线,我想保持我的可变空间整洁。
我想做这样的事情:
...a, b, and c populated as lists earlier in code...
using ix=getindex(): print(a[ix],b[ix],c[ix])
...now ix is no longer defined...
变量 ix 在一行之外是未定义的。
也许这个伪代码更清楚:
...a and b are populated lists earlier in code...
{ix=getindex(); answer = f(a[ix]) + g(b[ix])}
其中 ix 不存在于括号之外。
原文由 Michael Ehrlichman 发布,翻译遵循 CC BY-SA 4.0 许可协议
Comprehensions 和 generator expressions 有它们自己的范围,所以你可以把它放在其中之一:
但你真的不必担心那种事情。这是 Python 的卖点之一。
对于那些使用 Python 2 的人:
考虑使用 Python 3,这样您就不
print
作为语句处理。