python - 如何通过输入列表名称和对象来显示列表中有多少对象?
问题描述
我想编写一个程序来显示特定列表中特定对象的计数。用户输入列表名称,然后输入对象,然后获取计数。
这是我的代码:
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
解决方案
正如 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()
,但即使那样你仍然会滥用变量。
推荐阅读
- excel - 如何设置列表框的宽度和大小固定
- sql - sql子字符串包含
- sql-server - SQL 递归 CTE 图遍历
- windows - Windows 服务用户帐户无法访问证书存储
- etl - 如何使用 Kettle 处理字段中的换行
- cordova - 使用 cordova 和 Ionic 构建的 UWP 不考虑主机文件
- delphi - 以编程方式更改快捷方式图标
- javascript - 锚点href vs 角度路由器链接
- javascript - 如何从 javascript 中的创建订阅 API 调用中检索 Stripe 订阅 ID
- python - Selenium:通过'option selected value'选择,默认时不存在