python - 如果字符串与列表名称匹配,则将数字附加到列表
问题描述
我正在尝试编写如下 Python 程序:
list_a = []
list_b = []
list_c = []
listName = str(input('insert list name: '))
listValue = int(input('insert value: '))
listName.append(listValue)
但不幸的是“listName.append()”不起作用。
仅使用 IF 函数,如:
if listName == 'list_a':
list_a.append(listValue)
不切实际,因为我实际上正在处理 600 多个列表...
有没有其他方法可以让这样的事情正常工作?
非常感谢您的帮助!
非常感谢您提前!!
解决方案
当你想使用变量名来保存数据时——比如股票的名称——你几乎肯定应该使用以数据为键的字典。如果您愿意,您仍然可以预先填充字典(尽管您不必这样做)。
您可以将现有代码更改为:
# all the valid names
names = ['list_a', 'list_b', 'list_c']
# pre-populate a dictionary with them
names = {name:[] for name in names}
# later you can add data to the arrays:
listName = str(input('insert list name: '))
listValue = int(input('insert value: '))
# append value
names[listName].append(listValue)
有了这个,您的所有数据都在一个结构中。循环遍历它会很容易,使总和/平均值等汇总统计数据起作用。拥有一个包含 600 个键的字典没什么大不了的,但是拥有 600 个单独的变量会造成混乱。
如果您尝试添加一个不存在的名称,这将引发一个关键错误,如果有可能,您可以在 try 块中捕获该名称。
推荐阅读
- php - 查询在线工作但不在本地机器上
- apache-spark - Apache Spark 的最佳 NLP 工具
- javascript - 在表“test.users”上找不到索引“硬币”
- spring-boot - 使用 @Aspect 的 Spring AOP 实现不适用于我的项目
- .htaccess - 子域的htaccess重定向
- oracle - 我希望这个触发器在审计表中插入数据并抛出错误。但这只会引发错误,但不会插入数据
- python - ModuleNotFoundError:Scrapy 中没有名为“”的模块
- chef-infra - 刀库刷新命令无法搜索查询
- excel - VBA - VBA 运行时无法打开工作表
- javascript - 使用 Ajax 插入和获取数据插入工作但 fetch 功能不工作