首页 > 解决方案 > 如何通过输入列表名称和对象来显示列表中有多少对象?

问题描述

我想编写一个程序来显示特定列表中特定对象的计数。用户输入列表名称,然后输入对象,然后获取计数。

这是我的代码:

list_1 = [1, 2, 4, 2, 5, 6, 7, 3, 5, 6, 3, 2, 1, 7, 8, 9, 3, 6, 5, 3, 4]

list_2 = [12, 14, 13 , 11, 16, 15, 17, 18, 18, 19, 17, 15, 19, 11, 12, 14, 13]

def count_objects(wlist):    
    read_o = int(input("input object: "))
    print(wlist.count(read_o))

getList = input("input list: ")
count_objects(getList)

但它说:

Traceback (most recent call last):
 line 6, in <module>
    count(wlist)
  line 4, in count
    print(wlist.count(read_o))
TypeError: must be str, not int 

标签: python

解决方案


正如 Juanpa Arrivillaga 所说:

这里的基本问题是您依赖于变量名。

如果您想将用户输入映射到程序中的某些预定义值,您可能应该使用字典。可以这样做:

lists = {
    # These keys can be whatever you want
    '1': [1, 2, 4, 2, 5, 6, 7, 3, 5, 6, 3, 2, 1, 7, 8, 9, 3, 6, 5, 3, 4],
    '2': [12, 14, 13 , 11, 16, 15, 17, 18, 18, 19, 17, 15, 19, 11, 12, 14, 13],
}

def count_objects(wlist):    
    read_o = int(input("input object: "))
    print(wlist.count(read_o))

getList = input(f"input list: (valid inputs are: {list(lists)})\n")
count_objects(lists[getList])

这是对您的代码的极少编辑,可以进行相当多的改进。一旦你让它工作,我会建议前往https://codereview.stackexchange.com以获得反馈。

如果您真的想使用用户输入访问代码中的变量,您可以使用eval它,但我强烈建议您不要这样做。globals()稍微好一点的方法是在or dicts中查找它locals(),但即使那样你仍然会滥用变量。


推荐阅读