Python check if all elements of a list are the same type
How is possible in python to check (without checking individually every element if possible) if the elements of a list are of the same type?
For example, I would like to have a function to check that every element of this list is integer (which is clearly false):
x=[1, 2.5, 'a']
def checkIntegers(x):
# return true if all elements are integers, false otherwise
Try using all
in conjunction with isinstance
:
all(isinstance(x, int) for x in lst)
You can even check for multiple types with isinstance
if that is desireable:
all(isinstance(x, (int, long)) for x in lst)
Not that this will pick up inherited classes as well. eg:
class MyInt(int):
pass
print(isinstance(MyInt('3'),int)) #True
If you need to restrict yourself to just integers, you could use all(type(x) is int for x in lst)
. But that is a VERY rare scenario.
A fun function you could write with this is one which would return the type of the first element in a sequence if all the other elements are the same type:
def homogeneous_type(seq):
iseq = iter(seq)
first_type = type(next(iseq))
return first_type if all( (type(x) is first_type) for x in iseq ) else False
This will work for any arbitrary iterable, but it will consume "iterators" in the process.
Another fun function in the same vein which returns the set of common bases:
import inspect
def common_bases(seq):
iseq = iter(seq)
bases = set(inspect.getmro(type(next(iseq))))
for item in iseq:
bases = bases.intersection(inspect.getmro(type(item)))
if not bases:
break
return bases
>>> def checkInt(l):
return all(isinstance(i, (int, long)) for i in l)
>>> checkInt([1,2,3])
True
>>> checkInt(['a',1,2,3])
False
>>> checkInt([1,2,3,238762384762364892364])
True
Using any()
, no need to traverse whole list. Just break as soon as object which is not int
or long
is found:
>>> not any(not isinstance(y,(int,long)) for y in [1,2,3])
True
>>> not any(not isinstance(y,(int,long)) for y in [1,'a',2,3])
False
链接地址: http://www.djcxy.com/p/54234.html
上一篇: 处理一个列表或单个整数作为参数