如何在python中定义一个临时变量?

新手上路,请多包涵

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 许可协议

阅读 964
2 个回答

Comprehensions 和 generator expressions 有它们自己的范围,所以你可以把它放在其中之一:

 >>> def getindex():
...     return 1
...
>>> a,b,c = range(2), range(3,5), 'abc'
>>> next(print(a[x], b[x], c[x]) for x in [getindex()])
1 4 b
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

但你真的不必担心那种事情。这是 Python 的卖点之一。

对于那些使用 Python 2 的人:

 >>> print next(' '.join(map(str, [a[x], b[x], c[x]])) for x in [getindex()])
1 4 b

考虑使用 Python 3,这样您就不 print 作为语句处理。

原文由 TigerhawkT3 发布,翻译遵循 CC BY-SA 3.0 许可协议

python 是否具有“临时”或“非常本地”的变量功能?

是的,它被称为一个块,例如一个函数:

 def foo(*args):
    bar = 'some value' # only visible within foo
    print bar # works
foo()
> some value
print bar # does not work, bar is not in the module's scope
> NameError: name 'bar' is not defined

请注意,任何值都是临时的,只要名称绑定到它,它就可以保证保持分配状态。您可以通过调用 del 解除绑定:

 bar = 'foo'
print bar # works
> foo
del bar
print bar # fails
> NameError: name 'bar' is not defined

请注意,这不会直接释放字符串对象 'foo' 。这是 Python 的垃圾收集器的工作,它将在您之后进行清理。然而,在几乎所有情况下,都不需要明确处理解除绑定或 gc。只需使用变量并享受 Python 的生活方式。

原文由 miraculixx 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏