首页 > 解决方案 > 如果字符串与列表名称匹配,则将数字附加到列表

问题描述

我正在尝试编写如下 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 多个列表...

有没有其他方法可以让这样的事情正常工作?

非常感谢您的帮助!

非常感谢您提前!!

标签: pythonstringlistmatch

解决方案


当你想使用变量名来保存数据时——比如股票的名称——你几乎肯定应该使用以数据为键的字典。如果您愿意,您仍然可以预先填充字典(尽管您不必这样做)。

您可以将现有代码更改为:

# 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 块中捕获该名称。


推荐阅读