当前位置: 首页 > 图灵资讯 > 行业资讯> python如何判断变量是否是元组

python如何判断变量是否是元组

来源:图灵python
时间: 2025-03-07 22:09:25

Python的数据类型有:数字(int)、浮点(float)、字符串(str),列表(list)、元组(tuple)、字典(dict)、集合(set)。

判断一般采用以下方法:

1、isinstance(参数1,参数2)

描述:该函数用于判断变量(参数1)是否为已知的变量类型(参数2)与type()相似。

参数1:变量

参数2:它可以是由它们组成的直接或间接类名、基本类型或元组。

返回值:如果对象类型和参数二类型(classinfo)相同则返回 True,否则返回 False。

例子:

#判断变量类型的函数
deftypeof(variate):
type=None
ifisinstance(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=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)))

返回:

1af092b935db083454750431c3f9fda.png

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=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)))

返回:

cf01b9364168ff4bcfc183a6dbf3ac8.png

补充:

isinstance() 与 type() 区别:

type() 不考虑继承关系,子类不会被认为是父类。

isinstance() 考虑继承关系,子类将被视为父类。

如果要判断两种类型是否相同,建议使用 isinstance()。

python学习网,免费在线学习python平台,欢迎关注!

上一篇:

python 怎么引入类

下一篇:

返回列表