How can I make multiple empty lists in python?

2020-02-02 11:41发布

How can I make many empty lists without manually typing

list1=[] , list2=[], list3=[]

Is there a for loop that will make me 'n' number of such empty lists?

7条回答
乱世女痞
2楼-- · 2020-02-02 12:39

Sorry that I am two years late, but maybe I can still help some other people.

The code below will dynamically 'create' itself. For every iteration, the following command will issued:

listnumber = []

Where number is the value of i in the loop.

x = 3 # amount of lists you want to create
for i in range(1, x+1):
    command = "" # this line is here to clear out the previous command
    command = "list" + str(i) + " = []"
    exec(command)

The result of this particular piece of code is three variables: list1, list2 and list3 being created and each assigned an empty list.

You can generalize this to make practically anything you want. Do note that you cannot put this into a function as far as I know, because of how variables and global variables work.

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)

I hope I helped!

查看更多
登录 后发表回答