将变量名称存储在列表中

时间:2019-08-05 17:47:12

标签: python

我有以下列表:

lst_gws = ["gw1", "gw2", "gw3"]

gw1 = ["gw1-123", "gw1-234"]
gw2 = ["gw2-445", "gw2-332"]
gw3 = ["gw3-257", "gw3-321"]

是否可以遍历列表并打印出每个列表的值,例如:

for i in lst_gws:
    print i

但打印实际值而不是名称。

3 个答案:

答案 0 :(得分:2)

您可以这样做:

for i in lst_gws:
    print(locals()[i])

将按预期打印出来(locals()允许您访问任何局部变量):

>>> lst_gws = ["gw1", "gw2", "gw3"]
>>>
>>> gw1 = ["gw1-123", "gw1-234"]
>>> gw2 = ["gw2-445", "gw2-332"]
>>> gw3 = ["gw3-257", "gw3-321"]
>>> for i in lst_gws:
...     print(locals()[i])
...
['gw1-123', 'gw1-234']
['gw2-445', 'gw2-332']
['gw3-257', 'gw3-321']

答案 1 :(得分:2)

如何使用字典?

lst_gws = {
    "gw1" : ["gw1-123", "gw1-234"],
    "gw2" : ["gw2-445", "gw2-332"],
    "gw3" : ["gw3-257", "gw3-321"],
}

for name in lst_gws:
    print lst_gws[name]

答案 2 :(得分:1)

您可以使用locals()globals()访问局部和全局变量字典。

它们是字典,其中键是变量的名称,而值是其值...

x = 3
y = 2
z = [1, 2, 3]
vars = ["x", "y", "z"]

for name in vars:
    print(locals()[name])