如何获取用户输入来引用 Python 中的变量?
我想获取用户输入来引用我的代码中的某些列表。我认为这叫做命名空间?那么,假设他们输入“list1”或“list2”,我需要对这段代码做什么才能打印用户输入的任何内容?
list1 = ['cat', 'dog', 'juice']
list2 = ['skunk', 'bats', 'pogo stick']
x = raw_input('which list would you like me to print?')
我计划有很多这样的列表,因此一系列 if...then 语句看起来不守规矩。
I would like to get user input to refer to some list in my code. I think it's called namespace? So, what would I have to do to this code for me to print whatever the user inputs, supposing they input 'list1' or 'list2'?
list1 = ['cat', 'dog', 'juice']
list2 = ['skunk', 'bats', 'pogo stick']
x = raw_input('which list would you like me to print?')
I plan to have many such lists, so a series of if...then statements seems unruly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我现在能想到的情况下,拥有一个包含您希望用户能够引用的内容的字典可能会更好,例如:
事实上,您可以利用内置的 globals(),如下所示:
In the cases I can think of right now it would probably be better to have a dictionary containing what you want the user to be able to reference, for example:
In fact, you can take advantage of the built-in globals(), like this:
使用字典的总体思路是好的,但最好的具体实现可能类似于:
使用,例如:
要点是,当您要求用户从有限数量的可能性中选择一个时,你总是想检查选项是否是其中之一(毕竟很容易拼写错误等),如果不是,则准确提示(给出可用选项的列表)并再给用户一次机会。
各种改进(例如,有最大尝试次数,之后您决定用户无法键入并随机选择一个;-)保留为(不太难但也不太有趣;-)练习为读者。
The general idea of using a dict is good, but the best specific implementation is probably something like:
To be used, e.g., as:
The point is that, when you're asking the user to select one among a limited number of possibilities, you'll always want to check that the choice was one of them (it is after all easy to mis-spell, etc), and, if not, prompt accurately (giving the list of available choices) and give the user another chance.
All sorts of refinements (have a maximum number of attempts, for example, after which you decide the user just can't type and pick one at random;-) are left as (not too hard but not too interesting either;-) exercises for the reader.