问题
I would like to let the user define the name of a list to be used in the code, so I have been using an input function. I want the user's response to the input function to become the name of the list. I tried the following:
a = input("What would you like the name of the list to be? ")
a = []
However, this named the list "a" rather than whatever string the user had responded to the input function. How can I let the user name the list? Is there anyway to do this?
回答1:
The correct way to accomplish what you want here is a dict
of lists:
>>> lists = {}
>>> lists['homework'] = [40, 60, 70]
>>> lists['tests'] = [35, 99, 20]
>>> lists
{'tests': [35, 99, 20], 'homework': [40, 60, 70]}
>>>
When you can ask for input, the input
function (raw_input
in Python 2.x) returns a string, which you can make the key of the dictionary.
回答2:
A direct answer to your question is that you can use vars()
to access your variable scope:
list_name = input("What would you like the name of the list to be?")
vars()[list_name] = []
Then if you enter "foo" at the prompt, you will have a variable named foo.
An indirect answer is that, as several other users have told you, you don't want to let the user choose your variable names, you want to be using a dictionary of lists, so that you have all the lists that users have created together in one place.
A program where variable names are chosen at runtime is a program that can never be bug-free. For instance, if the user types "input" into your prompt, you will redefine your input function, so that when that user or another tries to create another list, what you will get instead is an error:
>>> list_name = input("What would you like the name of the list to be?")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
来源:https://stackoverflow.com/questions/6119790/naming-lists-using-user-input