簡體   English   中英

如何在python中定義臨時變量?

[英]How to define a temporary variable in 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不存在於括號外。

理解和生成器表達式有自己的范圍,因此您可以將其放在其中一個:

>>> 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作為語句處理。

從技術上講,這不是一個答案,但是:不要過多擔心臨時變量,它們只在本地范圍內有效(在您的情況下很可能是函數),垃圾收集器在該函數完成后立即刪除它們。 python中的一個襯里主要用於字典和列表推導。

如果您真的想在一行中執行它,請使用lambda ,它幾乎是內聯函數的關鍵字

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 livestyle。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM