如何在python中增加列表的名称

1 python naming list

我希望能够增加列表的名称,以便创建多个空列表.

例如,我想要.

List_1 = [] 
List_2 = []
...
List_x = []
Run Code Online (Sandbox Code Playgroud)

我一直在努力:

for j in range(5):            #set up loop
  list_ = list_ + str(j)     # increment the string list so it reads list_1, list_2, ect
  list_ = list()             # here I want to be able to have multiple empty lists with unique names
  print list_
Run Code Online (Sandbox Code Playgroud)

Don*_*ner 15

正确的方法是列出一个列表.

list_of_lists = []
for j in range(5):
   list_of_lists.append( [] )
   print list_of_lists[j]
Run Code Online (Sandbox Code Playgroud)

然后,您可以访问它们:

list_of_lists[2] # third empty list
list_of_lists[0] # first empty list
Run Code Online (Sandbox Code Playgroud)

如果你真的想这样做,尽管你可能不应该这样做,你可以使用exec:

for j in range(5):
    list_name = 'list_' + str(j)
    exec(list_name + ' = []')
    exec('print ' + list_name)
Run Code Online (Sandbox Code Playgroud)

这会在字符串下创建名称list_name,然后用于exec执行该动态代码段.

  • +1,但强调"正确的方法是列出一个列表",并且不要使用`exec` /`locals`. (2认同)