[英]How to know if object is of str or list or dict or int?
I have a list of lists and then I'm extracting the last element from the list. 我有一个列表列表,然后我从列表中提取最后一个元素。 Now, how to know whether it's of type
str
or list
or dict
or int
? 现在,如何知道它是
str
类型还是list
或dict
还是int
?
list2 = response_list[0][-1]
print list2,type(list2)
print "not executing"
print list2
I have failed to match if that element is list
or str
by the following code: 如果该元素是
list
或str
,则我无法匹配以下代码:
list2 = response_list[0][-1]
if type(list2) == str() :
print list2,type(list2)
elif type(list2) == list() :
print list2,type(list2)
Since Python 2.2 , you should use this code: 从Python 2.2开始 ,您应该使用以下代码:
if isinstance(list2, (str, list, dict)):
isinstance()
takes a tuple as second argument and returns true
if the type is in the tuple. isinstance()
将元组作为第二个参数,如果类型在元组中,则返回true
。
Actually the type function works as 实际上类型函数的作用是
>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>
For comparision you can use isinstance()
function which returns True/False
对于比较,您可以使用返回
True/False
isinstance()
函数
list2 = response_list[0][-1]
if isinstance(list2,str):
print list2,type(list2)
elif isinstance(list2,list):
print list2,type(list2)
You can rearrange your code like this, 您可以像这样重新安排代码,
list2 = response_list[0][-1]
if type(list2) == str:
print list2,type(list2)
elif type(list2) == list:
print list2,type(list2)
Try the below using type function, pretty clean yeah? 尝试下面使用类型功能,非常干净是啊?
dict, str, tuple, int
if type(d) is dict:
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.