【问题标题】:Is there a way to check if two lists of objects contain only the same type of object in Python?有没有办法检查两个对象列表是否仅包含 Python 中相同类型的对象?
【发布时间】:2021-01-05 13:53:55
【问题描述】:

例如:

class someObject:
    def __init__():
        pass
objone = someObject()
listone = []
listone.append(objone)
objtwo = someObject()
listtwo = []
listtwo.append(objtwo)

两个列表都有相同类型的对象,即 someObject,我想知道如何检查它。上面的场景应该返回 True,因为两个列表都有相同类型的对象,但如果 listone 为空,或者说,有一个字符串 以及对象,它将返回 False。

【问题讨论】:

    标签: python list compare


    【解决方案1】:

    check_lists 函数执行以下操作,它首先检查列表或相同长度,然后通过列表中的元素zips 并比较 itype 是否与 @ 相同987654325@。只有当所有人都是True 你得到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 更改为and。 @chepner 的 cmets 对此进行了解释。

    【讨论】:

    • 我不知道这是如何工作的,但它确实有效。谢谢你好心的陌生人
    • 我已经添加了一个简短的解释,如果对你有帮助,你可以标记为已解决
    • 这不包含子类。
    • isinstance 不是吗? @chepner
    • 对不起,我以为你用is 来比较ij 的类型。我会在这里使用and 而不是is 来验证两个对象是否具有相同的类型。 False is False 是真的,尽管它表明这两个对象具有相同的类型。
    【解决方案2】:

    使用 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
    

    【讨论】:

    • 这适用于单个对象,但在我的示例中它们位于列表中。
    • 这不包含子类。
    【解决方案3】:

    使用itertools.chainallisinstance

    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)):
        ...
    

    【讨论】:

    • chain 很聪明:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多