Naming Lists Using User Input

送分小仙女□ 提交于 2021-02-11 15:22:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!