AI可控遗忘:RAG系统中的数据生命周期管理实战
2026/6/7 9:27:03
在Python编程中,数据类型不符错误(通常是TypeError)会在以下常见情况下出现:
# 字符串和数字相加result="年龄:"+25# TypeError: can only concatenate str to str# 不兼容类型的运算result=10/"2"# TypeError: unsupported operand type(s)# 内置函数期望特定类型len(123)# TypeError: object of type 'int' has no len()sum(["1","2"])# TypeError: unsupported operand typeint("abc")# ValueError,但也是类型相关错误# 自定义函数参数类型不匹配defcalculate_square(n:int):returnn*n calculate_square("5")# 运行时TypeError# 对不支持的类型调用方法num=123num.append(4)# AttributeError/TypeErrortext="hello"text.update({})# AttributeErrormy_list=[1,2,3]my_list["key"]# TypeError: list indices must be integers# 错误的切片类型my_list[1.5:3]# TypeError: slice indices must be integers# 尝试迭代非可迭代对象foriin123:# TypeError: 'int' object is not iterablepass# 解包时类型不匹配a,b=123# TypeError: cannot unpack non-iterable int object"5">3# TypeError: '>' not supported between str and intNone<10# TypeErrorimportmath math.sqrt("16")# TypeErrorpow("2","3")# TypeError# f-string中的类型错误value="abc"f"结果是:{value+5}"# TypeError# %格式化中的类型不匹配"Value: %d"%"123"# TypeError: %d format requires a numberclassPerson:def__init__(self,name:str,age:int):self.name=name self.age=age Person(123,"25")# 参数类型与期望不符importpandasaspdimportnumpyasnp# pandas/numpy中的类型错误df=pd.DataFrame({"A":[1,2,3]})df["A"].mean()# 正常df["A"]=df["A"]+"text"# TypeErrordefsafe_add(a,b):ifnot(isinstance(a,(int,float))andisinstance(b,(int,float))):raiseTypeError("参数必须是数字类型")returna+bfromtypingimportUniondefprocess_value(value:Union[int,str])->str:returnstr(value)try:result=int(user_input)except(ValueError,TypeError)ase:print(f"转换失败:{e}")result=0# 确保类型正确age=int(input("输入年龄: "))# 可能引发ValueErrorscore=float("95.5")# 显式转换# 安全转换defto_int_safe(value):try:returnint(value)except(ValueError,TypeError):return0defvalidate_input(data):ifisinstance(data,dict):# 处理字典passelifisinstance(data,list):# 处理列表passelse:raiseTypeError("输入必须是字典或列表")调试这类错误时,使用type()函数检查变量类型,或使用IDE的调试工具查看变量类型,有助于快速定位问题。