0

我想做一个像这样的while循环

list=[]    
while x in range(r):
        list-x="something"

每次循环开始时,它都会创建一个带有数字 (x) 的新列表。因此,如果它循环超过 5 次,就会有不同的列表:list(1) list(2) list(3) list(4)。'

这甚至可能吗?

4

1 回答 1

4

You are able to do this with the vars() function:

for i in range(5):
    list_name = ''.join(['list', str(i)])
    vars()[list_name] = []

You can then reference each list:

print(list1)
--> []
print(list2)
--> []

etc...

You can also achieve this using the locals() or globals() functions as below:

for i in range(5):
    locals()['list{}'.format(i)] = []

Hope that helps!

于 2013-04-04T23:33:51.277 回答