Python: determining whether any item in sequence is equal to any other

前端 未结 5 1108
失恋的感觉
失恋的感觉 2021-01-04 19:40

I\'d like to compare multiple objects and return True only if all objects are not equal among themselves. I tried using the code below, but it doesn\'t work. If

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 20:28

    If the objects are all hashable, then you can see whether a frozenset of the sequence of objects has the same length as the sequence itself:

    def all_different(objs):
        return len(frozenset(objs)) == len(objs)
    

    Example:

    >>> all_different([3, 4, 5])
    True
    >>> all_different([3, 4, 5, 3])
    False
    

提交回复
热议问题