Python检查列表中的所有元素是否都属于同一类型 [英] Python check if all elements of a list are the same type

查看:1322
本文介绍了Python检查列表中的所有元素是否都属于同一类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中如何检查(如果可能,不单独检查每个元素)列表中的元素是否属于同一类型?

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

推荐答案

尝试使用 all isinstance 结合使用:

Try using all in conjunction with 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

这篇关于Python检查列表中的所有元素是否都属于同一类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆