检查列表的所有元素是否属于同一类型 [英] Check if all elements of a list are of the same type
问题描述
如何检查列表中的元素是否属于同一类型,而不单独检查每个元素(如果可能)?
How can I check if the elements of a list are of the same type, without checking individually every element if possible?
例如,我想要一个函数来检查此列表的每个元素是否都是整数(这显然是错误的):
For example, I would like to have a function to check that every element of this list is an integer (which is clearly false):
x = [1, 2.5, 'a']
def checkIntegers(x):
# return True if all elements are integers, False otherwise
推荐答案
尝试使用 all
结合 isinstance
:
all(isinstance(x, int) for x in lst)
如果需要,您甚至可以使用 isinstance
检查多种类型:
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. e.g.:
class MyInt(int):
pass
print(isinstance(MyInt('3'),int)) #True
如果您需要限制自己只能使用整数,您可以使用all(type(x) is int for x in lst)
.但这是一种非常罕见的情况.
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
这篇关于检查列表的所有元素是否属于同一类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!