我希望能够递增列表的名称,这样我就可以创建多个空列表。
例如,我想要。
List_1 = []
List_2 = []
...
List_x = []
我一直在与:
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_
请您参考如下方法:
执行此操作的正确方法是使用列表列表。
list_of_lists = []
for j in range(5):
list_of_lists.append( [] )
print list_of_lists[j]
然后,您可以通过以下方式访问它们:
list_of_lists[2] # third empty list
list_of_lists[0] # first empty list
如果您真的想要这样做,尽管您可能不应该这样做,您可以使用exec:
for j in range(5):
list_name = 'list_' + str(j)
exec(list_name + ' = []')
exec('print ' + list_name)
这会在 list_name 下的字符串中创建名称,然后使用 exec 执行该动态代码。
