这篇文章主要介绍python判断数据类型是不是字典的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
python的数据类型有:数字int)、浮点float)、字符串str),列表list)、元组tuple)、字典dict)、集合set)。
一般通过以下方法进行判断:
1、isinstance参数1,参数2)
描述:该函数用来判断一个变量(参数1)是否是已知的变量类型参数2) 类似于type)
参数1:变量
参数2:可以是直接或间接类名、基本类型或者由它们组成的元组。
返回值: 如果对象的类型与参数二的类型(classinfo)相同则返回True,否则返回False。
例子:
#判断变量类型的函数
def typeofvariate):
type=None
if isinstancevariate,int):
type = "int"
elif isinstancevariate,str):
type = "str"
elif isinstancevariate,float):
type = "float"
elif isinstancevariate,list):
type = "list"
elif isinstancevariate,tuple):
type = "tuple"
elif isinstancevariate,dict):
type = "dict"
elif isinstancevariate,set):
type = "set"
return type
# 返回变量类型
def getTypevariate):
arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
vartype = typeofvariate)
if not vartype in arr):
return "未知类型"
return arr[vartype]
#判断变量是否为整数
money=120
print"{0}是{1}".formatmoney,getTypemoney)))
#判断变量是否为字符串
money="120"
print"{0}是{1}".formatmoney,getTypemoney)))
money=12.3
print"{0}是{1}".formatmoney,getTypemoney)))
#判断变量是否为列表
students=['studentA']
print"{0}是{1}".formatstudents,getTypestudents)))
#判断变量是否为元组
students='studentA','studentB')
print"{0}是{1}".formatstudents,getTypestudents)))
#判断变量是否为字典
dictory={"key1":"value1","key2":"value2"}
print"{0}是{1}".formatdictory,getTypedictory)))
#判断变量是否为集合
apple={"apple1","apple2"}
print"{0}是{1}".formatapple,getTypeapple)))
返回:
2、通过与已知类型的常量进行比较
例子:
#判断变量类型的函数
def typeofvariate):
type1 = ""
if typevariate) == type1):
type1 = "int"
elif typevariate) == type"str"):
type1 = "str"
elif typevariate) == type12.3):
type1 = "float"
elif typevariate) == type[1]):
type1 = "list"
elif typevariate) == type)):
type1 = "tuple"
elif typevariate) == type{"key1":"123"}):
type1 = "dict"
elif typevariate) == type{"key1"}):
type1 = "set"
return type1
#返回变量类型
def getTypevariate):
arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
vartype = typeofvariate)
if not vartype in arr):
return "未知类型"
return arr[vartype]
#判断变量是否为整数
money=120
print"{0}是{1}".formatmoney,getTypemoney)))
#判断变量是否为字符串
money="120"
print"{0}是{1}".formatmoney,getTypemoney)))
money=12.3
print"{0}是{1}".formatmoney,getTypemoney)))
#判断变量是否为列表
students=['studentA']
print"{0}是{1}".formatstudents,getTypestudents)))
#判断变量是否为元组
students='studentA','studentB')
print"{0}是{1}".formatstudents,getTypestudents)))
#判断变量是否为字典
dictory={"key1":"value1","key2":"value2"}
print"{0}是{1}".formatdictory,getTypedictory)))
#判断变量是否为集合
apple={"apple1","apple2"}
print"{0}是{1}".formatapple,getTypeapple)))
返回:
isinstance) 与 type) 区别:
type) 不会认为子类是一种父类类型,不考虑继承关系。
isinstance) 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance)。


