我们可以在python中使用变量名称中的变量

时间:2016-03-30 12:13:02

标签: python

我正在尝试在python中创建一个变量,前缀为list,然后编号将在脚本中动态生成。例如

我正在尝试使用list10,其中list是前缀,10是动态生成的数字。

在TCL,我们给予

list${i}

在python中也有相同的方式吗?

2 个答案:

答案 0 :(得分:4)

这样做的pythonic方法是创建一个字典来存储列表,并将生成的名称作为字典的键:

d = {}
d['list1'] = [1, 2, 3]
d['list2'] = ['a', 'b', 'c']

编辑:生成密钥名称

你可以创建这样的键:

key = 'list' + str(1)  # or whatever number you are using
d[key] = [your list]

结束编辑

或者,如果您不是真的需要知道名称,请将列表存储在列表中并按索引检索它们:

lists = [[1, 2, 3], ['a', 'b', 'c']]

答案 1 :(得分:0)

您可以使用locals()vars()globals()并在那里注入您的变量名称。例如。

>>> list10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'list10' is not defined
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], '__name__': '__main__', '__doc__': None}
>>> locals()['list10'] = []
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'list10': [], '__package__': None, 'x': [], '__name__': '__main__', '__doc__': None}
>>> list10
[]

通常情况下,如果您正在做这样的事情,那么使用字典存储变量名称和值可能会更好。

例如。

>>> my_lists = {}
>>> my_lists['list10'] = []

然后当你想要查找它时,你可以.get()如果你想要一个不存在的变量名称的健壮性,或者如果你要自己防止不存在的话,可以直接访问它。 / p>

>>> the_list_i_want = my_lists.get('list10')
>>> the_list_i_want = my_lists['list10']  # Will raise a KeyError if it does not exist