Python: check for data type in list

拜拜、爱过 提交于 2021-02-04 16:23:06

问题


Is there a way to check if an instance of a specific data type is present in a list / dictionary, without explicitly checking every element / key?

I suspect the answer is no. If it does exist, though, I imagine it would be similar to the way you can use the in operator to search for specific elements / keys, like this:

3 in [1, 2, 3] # => True

except you'd be checking for an instance of a data type rather than a some specific value, like this:

int in [1,"a", 3.4] # => True

Any ideas?


回答1:


Well in is actually syntactic sugar for __contains__, which does iterate over the contents of the list.

If you would like to use in to check for types instead; you could implement your own data structure (subclassing list) and override __contains__ to check for types:

class MyList(list):
    def __contains__(self, typ):
        for val in self:
            if isinstance(val, typ):
                return True
        return False

x = MyList([1, 2, 'a', 3])

print float in x # False
print str in x   # True

You could also take advantage of the any function:

def __contains__(self, typ):
    return any(isinstance(val, typ) for val in self)

print int in MyList([1, "a", 3.4]) # True
print int in MyList(["a", 3.4])    # False

As for whether this is doable without checking every element - no, it's not. In the worst case scenario, you do end up checking every element.




回答2:


I think you can use isinstance(element, type).

I made a function:

def checkType(a_list):
    for element in a_list:
        if isinstance(element, int):
            print("It's an Integer")
        if isinstance(element, str):
            print("It's an string")
        if isinstance(element, float):
            print("It's an floating number")

numbers = [1, 2, 3]
checkType(numbers)

This outputs:

It's an Integer
It's an Integer
It's an Integer


来源:https://stackoverflow.com/questions/46919820/python-check-for-data-type-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!