使用in运算符查找列表元素时遇到的匹配异常问题
问题分析:
in运算符判断列表元素存在性失败的原因 你的代码核心问题是类型不匹配:
- 向列表
productNums中添加元素时,直接使用input()的返回值,而input()默认返回字符串类型,所以列表里的所有元素都是字符串。 - 但你查找的
numFind是通过int(input(...))转换后的整数类型。
在Python中,整数和字符串属于不同的数据类型,即使数值相同(比如整数5和字符串"5"),也会被判定为不同的元素,因此numFind in productNums永远返回False,导致程序误判。
修正方案
有两种简单的解决思路:
方案1:将输入的数字转为整数后存入列表
修改添加元素的代码,把input()的结果转成整数再加入列表:
productNums = [] nums = int(input("How many numbers should be in your list?")) while nums > 0: # 转换输入为整数后存入列表 productNums.append(int(input("Add a number: "))) nums -= 1 numFind = int(input("What number are you trying to find? ")) if numFind in productNums: print("This product number is in the list") elif numFind not in productNums: print("Ahh, sorry. This product number is NOT in this list!") else: print("Huh, you're confusing me now, check your numbers pal!")
方案2:将查找的数字转为字符串后再判断
保持列表元素为字符串,把要查找的numFind转成字符串进行判断:
productNums = [] nums = int(input("How many numbers should be in your list?")) while nums > 0: productNums.append(input("Add a number: ")) nums -= 1 numFind = int(input("What number are you trying to find? ")) # 将查找目标转为字符串后匹配 if str(numFind) in productNums: print("This product number is in the list") elif str(numFind) not in productNums: print("Ahh, sorry. This product number is NOT in this list!") else: print("Huh, you're confusing me now, check your numbers pal!")
两种方案都能解决类型不匹配的问题,推荐方案1,因为既然你处理的是数字,用整数类型存储更符合逻辑。
内容的提问来源于stack exchange,提问作者SaviorTech
相关产品推荐
相关产品推荐

