lin*_*llo 43 python types list
如果列表的元素属于同一类型,python中如何检查(如果可能的话,不单独检查每个元素)?
例如,我想有一个函数来检查这个列表的每个元素是否为整数(这显然是假的):
x=[1, 2.5, 'a']
def checkIntegers(x):
# return true if all elements are integers, false otherwise
Run Code Online (Sandbox Code Playgroud)
mgi*_*son 99
尝试all
结合使用isinstance
:
all(isinstance(x, int) for x in lst)
Run Code Online (Sandbox Code Playgroud)
如果需要,您甚至可以检查多种类型isinstance
:
all(isinstance(x, (int, long)) for x in lst)
Run Code Online (Sandbox Code Playgroud)
并不是说这也会获得继承的类.例如:
class MyInt(int):
pass
print(isinstance(MyInt('3'),int)) #True
Run Code Online (Sandbox Code Playgroud)
如果你需要将自己限制为只有整数,你可以使用all(type(x) is int for x in lst)
.但这是非常罕见的情况.
如果所有其他元素都是相同的类型,那么你可以用这个函数写一个有趣的函数,它会返回序列中第一个元素的类型:
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
Run Code Online (Sandbox Code Playgroud)
这适用于任何任意迭代,但它将消耗过程中的"迭代器".
另一个有趣的功能,它返回一组共同基础:
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
Run Code Online (Sandbox Code Playgroud)
使用any()
,无需遍历整个列表。只要没有int
或long
找到的对象就中断:
>>> 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
Run Code Online (Sandbox Code Playgroud)
结合已经给出的一些答案,使用 map()、type() 和 set() 的组合提供了一个恕我直言相当可读的答案。假设不检查类型多态性的限制是可以的。也不是计算效率最高的答案,但它可以轻松检查所有元素是否属于同一类型。
# To check whether all elements in a list are integers
set(map(type, [1,2,3])) == {int}
# To check whether all elements are of the same type
len(set(map(type, [1,2,3]))) == 1
Run Code Online (Sandbox Code Playgroud)