python判断变量是否为列表的方法
这篇文章主要介绍了python判断变量是否为列表的方法,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。
python的数据类型有:数字(int)、浮点(float)、字符串(str),列表(list)、元组(tuple)、字典(dict)、集合(set)。
一般通过以下方法进行判断:
1、isinstance(参数1,参数2)
描述:该函数用来判断一个变量(参数1)是否是已知的变量类型(参数2) 类似于type()
参数1:变量
参数2:可以是直接或间接类名、基本类型或者由它们组成的元组。
返回值:如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。
例子:
#判断变量类型的函数deftypeof(variate):type=Noneifisinstance(variate,int):type="int"elifisinstance(variate,str):type="str"elifisinstance(variate,float):type="float"elifisinstance(variate,list):type="list"elifisinstance(variate,tuple):type="tuple"elifisinstance(variate,dict):type="dict"elifisinstance(variate,set):type="set"returntype#返回变量类型defgetType(variate):arr={"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}vartype=typeof(variate)ifnot(vartypeinarr):return"未知类型"returnarr[vartype]#判断变量是否为整数money=120print("{0}是{1}".format(money,getType(money)))#判断变量是否为字符串money="120"print("{0}是{1}".format(money,getType(money)))money=12.3print("{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、通过与已知类型的常量进行比较
例子:
#判断变量类型的函数deftypeof(variate):type1=""iftype(variate)==type(1):type1="int"eliftype(variate)==type("str"):type1="str"eliftype(variate)==type(12.3):type1="float"eliftype(variate)==type([1]):type1="list"eliftype(variate)==type(()):type1="tuple"eliftype(variate)==type({"key1":"123"}):type1="dict"eliftype(variate)==type({"key1"}):type1="set"returntype1#返回变量类型defgetType(variate):arr={"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}vartype=typeof(variate)ifnot(vartypeinarr):return"未知类型"returnarr[vartype]#判断变量是否为整数money=120print("{0}是{1}".format(money,getType(money)))#判断变量是否为字符串money="120"print("{0}是{1}".format(money,getType(money)))money=12.3print("{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判断变量是否为列表的方法内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。