如何解决有没有办法在 Python 中检查两个对象列表是否只包含相同类型的对象?
例如:
class someObject:
def __init__():
pass
objone = someObject()
listone = []
listone.append(objone)
objtwo = someObject()
listtwo = []
listtwo.append(objtwo)
两个列表都有相同类型的对象,即 someObject,我想知道如何检查它。上面的场景应该返回 True,因为两个列表都有相同类型的对象,但是如果 listone 是空的,或者说,有一个 String with 对象,它会返回 False。
解决方法
check_lists
函数执行以下操作,它首先检查列表或长度是否相同,然后通过列表中的元素 zips
并比较 {{1} 的 type
1}} 与 i
相同。仅当全部为 j
时,您才会得到 True
else True
。
下面的例子展示了一些测试。
False
编辑:
将 class someObject:
def __init__(self):
pass
objone = someObject()
listone = []
listone.append(objone)
objtwo = someObject()
listtwo = []
listtwo.append(objtwo)
def check_lists(listone,listtwo):
return len(listone) == len(listtwo) and all(isinstance(i,someObject) and isinstance(j,someObject) for i,j in zip(listone,listtwo))
print(check_lists(listone,listtwo)) # True
listtwo.append('string')
print(check_lists(listone,listtwo)) # False
更改为 is
。 @chepner 的评论对此进行了解释。
使用 type()
>>> type(objone) == type(objtwo)
True
>>> type(objone) == type("some String")
False
# here is how
>>> list_one_types = [type(i) for i in listone]
>>> list_two_types = [type(i) for i in listtwo]
>>> list_one_types = set(list_one_types)
>>> list_two_types = set(list_two_types)
>>> list_one_types
{<class '__main__.someObject'>}
>>> list_two_types
{<class '__main__.someObject'>,<class 'str'>}
>>> list_one_types == list_two_types
False
,
使用 itertools.chain
、all
和 isinstance
。
from itertools import chain
if all(isinstance(x,someObject) for x in chain(listone,listtwo)):
...
如果事先不知道涉及到哪种类型,就直接获取第一个对象(验证两个列表都非空后):
if listone and listtwo and all(isinstance(x,type(listone[0])) for x in chain(listone,listtwo)):
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。