简体   繁体   English

如何知道对象是str还是list或dict还是int?

[英]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类型还是listdict还是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: 如果该元素是liststr ,则我无法匹配以下代码:

    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.

相关问题 将 [{str:int}, {str:int}, ... ] 的字典列表转换为 {str:int} 的单个字典 - Convert a list of dict of [{str:int}, {str:int}, ... ] to a single dict of {str:int} 描述符“值”需要一个“ dict”对象,但接收到一个“ int” /“ str” Python - descriptor 'values' requires a 'dict' object but received a 'int'/'str' python 为什么对str或int进行子类化的行为与对列表或dict进行子类化的行为不同? - Why subclassing a str or int behaves differently from subclising a list or dict? 如何使用json.dumps()将所有int转换为嵌套dict中的str? - how to convert all int to str in a nested dict with json.dumps()? 如何正确地将 list[str] 转换为 list[int]? - How to properly convert a list[str] into a list[int]? “Union[List[Any], Dict[Any, Any]]”的索引类型“Union[int, str]”无效; 预期类型“int” - Invalid index type “Union[int, str]” for “Union[List[Any], Dict[Any, Any]]”; expected type “int” 如何通过循环遍历 str 列表来创建 {str, [list of str]} 的字典? - How do I create a dict of {str, [list of str]} by looping over a list of str? 如何从字典中获取相当于 int 列表的内容 - How to get the equivalent of int list from a dict python如何知道对象属性(方法)以及如何知道dict的层次结构 - python how to know the object attributes(methods) and how to know the hierarchy of the dict 如何在 Python 列表中将 str 转换为 int - How to convert str to int in Python list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM