python的数据范例有:数字(int)、浮点(float)、字符串(str),列表(list)、元组(tuple)、字典(dict)、鸠合(set)。
平常经由过程以下要领举行推断:
1、isinstance(参数1,参数2)
形貌:该函数用来推断一个变量(参数1)是不是是已知的变量范例(参数2) 类似于type()
参数1:变量
参数2:可所以直接或间接类名、基础范例或许由它们构成的元组。
返回值: 假如对象的范例与参数二的范例(classinfo)雷同则返回True,不然返回False。
相干引荐:《Python视频教程》
例子:
#推断变量范例的函数 def typeof(variate): type=None if isinstance(variate,int): type = "int" elif isinstance(variate,str): type = "str" elif isinstance(variate,float): type = "float" elif isinstance(variate,list): type = "list" elif isinstance(variate,tuple): type = "tuple" elif isinstance(variate,dict): type = "dict" elif isinstance(variate,set): type = "set" return type # 返回变量范例 def getType(variate): arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"鸠合"} vartype = typeof(variate) if not (vartype in arr): return "未知范例" return arr[vartype] #推断变量是不是为整数 money=120 print("{0}是{1}".format(money,getType(money))) #推断变量是不是为字符串 money="120" print("{0}是{1}".format(money,getType(money))) money=12.3 print("{0}是{1}".format(money,getType(money))) #推断变量是不是为列表 students=['studentA'] print("{0}是{1}".format(students,getType(students))) #推断变量是不是为元组 students=('studentA','studentB') print("{0}是{1}".format(students,getType(students))) #推断变量是不是为字典 dictory={"key1":"value1","key2":"value2"} print("{0}是{1}".format(dictory,getType(dictory))) #推断变量是不是为鸠合 apple={"apple1","apple2"} print("{0}是{1}".format(apple,getType(apple)))
返回:
2、经由过程与已知范例的常量举行比较
例子:
#推断变量范例的函数 def typeof(variate): type1 = "" if type(variate) == type(1): type1 = "int" elif type(variate) == type("str"): type1 = "str" elif type(variate) == type(12.3): type1 = "float" elif type(variate) == type([1]): type1 = "list" elif type(variate) == type(()): type1 = "tuple" elif type(variate) == type({"key1":"123"}): type1 = "dict" elif type(variate) == type({"key1"}): type1 = "set" return type1 #返回变量范例 def getType(variate): arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"鸠合"} vartype = typeof(variate) if not (vartype in arr): return "未知范例" return arr[vartype] #推断变量是不是为整数 money=120 print("{0}是{1}".format(money,getType(money))) #推断变量是不是为字符串 money="120" print("{0}是{1}".format(money,getType(money))) money=12.3 print("{0}是{1}".format(money,getType(money))) #推断变量是不是为列表 students=['studentA'] print("{0}是{1}".format(students,getType(students))) #推断变量是不是为元组 students=('studentA','studentB') print("{0}是{1}".format(students,getType(students))) #推断变量是不是为字典 dictory={"key1":"value1","key2":"value2"} print("{0}是{1}".format(dictory,getType(dictory))) #推断变量是不是为鸠合 apple={"apple1","apple2"} print("{0}是{1}".format(apple,getType(apple)))
返回:
isinstance() 与 type() 区分:
type() 不会以为子类是一种父类范例,不斟酌继续关联。
isinstance() 会以为子类是一种父类范例,斟酌继续关联。
假如要推断两个范例是不是雷同引荐运用 isinstance()。
以上就是python怎样推断数据范例的细致内容,更多请关注ki4网别的相干文章!