You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 04:18:14