如何使用变量名创建数量未知的列表?

时间:2019-01-22 16:21:47

标签: python list exec python-3.7

我试图在python中定义一个能够创建数量未知的列表的定义,而我却碰上了这段代码:

name = "my_var" # This has to be a string, variables like my_var1, my_var2 
will be created.
value = "[]" # This also has to be a string, even when you want to assign 
integers! When you want to assign a string "3", you'd do this: value = "'3'"
 amount = 5 # This must be an integer. This many variables will be created 
(my_var1, my_var2 ... my_var5).

for i in range(1, amount+1):
    command_variable = ""
    command_variable = name + str(i) + " = " + value
    exec(command_variable)

有人告诉我,使用exec是不好的做法,而且,当代码在定义中时,创建的列表不可调用。 另一种选择是什么?

更新

我的问题被标记为在该线程上已回答:

How do I create a variable number of variables?

我不同意,因为我想创建与列表中的元素一样多的变量,并为它们分配名称以进行调用。

0 个答案:

没有答案