使用用户输入命名列表 [英] Naming Lists Using User Input

查看:79
本文介绍了使用用户输入命名列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户定义代码中要使用的列表的名称,因此我一直在使用输入函数.我希望用户对输入功能的响应成为列表的名称.我尝试了以下方法:

  a =输入(您希望列表的名称是什么?")a = [] 

但是,此命令将列表命名为"a",而不是用户对输入函数作出响应的任何字符串.如何让用户为列表命名?反正有这样做吗?

解决方案

在此处完成所需操作的正确方法是列表的 dict :

 >>>列表= {}>>>清单['家庭作业'] = [40、60、70]>>>list ['tests'] = [35,99,20]>>>清单{测试":[35、99、20],作业":[40、60、70]}>>> 

当您可以请求输入时, input 函数(在Python 2.x中为 raw_input )返回一个字符串,您可以将该字符串作为字典的键./p>

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?

解决方案

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.

这篇关于使用用户输入命名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆