[英]Lookup table in TensorFlow with key is string and value is list of strings
[英]Dynamically build key: value lookup for list of variables
假設我有一些變量:
a, b, c, d, e = range(5)
我想將這些變量的值保存在文件中以供以后檢查。 我認為做到這一點的一種方法是:
lookup = {
'a': a,
'b': b,
'c': c,
'd': d,
'e': e
}
就像您想象的那樣,使用大量變量,這可能會變得乏味。 而且,是的,我知道許多編輯器都具有簡化這種復制粘貼操作的功能。 但是我正在尋找動態構建鍵的標准“ Pythonic”方法:值查找,其中鍵是變量的名稱,而值是變量的值!
我想到了:
>>> {var.__name__: var for var in [a, b, c, d, e]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
AttributeError: 'int' object has no attribute '__name__'
我並不奇怪這沒有用,因為整數變量是常量(我不確定描述事物的確切方法):
>>> a = 1
>>> b = 1
>>> a is b
True
>>> b is a
True
>>> a == b
True
我該怎么做?
import itertools
data = range(5)
result = {f"a{count}": value for count, value in zip(itertools.count(1), data)}
print(result)
輸出:
{'a1': 0, 'a2': 1, 'a3': 2, 'a4': 3, 'a5': 4}
>>> from inspect import ismodule
>>> a = 1
>>> b = 1
>>> dict((k, v) for k, v in locals().items() if not k.startswith("__") and not callable(v) and not ismodule(v))
{'a': 1, 'b': 1}
但是要正確處理,您可能需要添加一些附加條件,並且還必須注意可變的對象或值,因為在這種情況下,這些對象或值會發生變異,並且您將不會保留較早的值以供以后檢查。 序列化或復制它們可能會有所幫助。
您可以從另一個方向處理它,並使用locals()
保存所有局部變量,例如
import json
def foo(a=None, bb=None):
ccc='lots of c'; de=42
print( json.dumps( locals() ))
foo()
生成{"a": null, "bb": null, "ccc": "lots of c", "de": 42}
( json.dumps
是序列化dict的一種方法,並且僅適用於可以轉換為JSON的簡單變量)
獲得一些變量的另一種方法是
print( json.dumps( dict( a=a, b=b, c=c) ))
這是從string
模塊使用ascii_lowercase
另一種方法:
import string
alphabets = iter(string.ascii_lowercase)
lookup = {next(alphabets): x for x in range(5)}
print(lookup)
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.