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

前端 未结 5 1066
失恋的感觉
失恋的感觉 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:12

    @Michael Hoffman's answer is good if the objects are all hashable. If not, you can use itertools.combinations:

    >>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd', 'a'], 2))
    False
    >>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd'], 2))
    True
    
    0 讨论(0)
  • 2021-01-04 20:15
    from itertools import combinations
    all(x != y for x, y in combinations(objs, 2))
    
    0 讨论(0)
  • 2021-01-04 20:23

    You can check that all of the items in a list are unique by converting it to a set.

    my_obs = [obj1, obj2, obj3]
    all_not_equal = len(set(my_obs)) == len(my_obs)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-04 20:31

    If the objects are unhashable but orderable (for example, lists) then you can transform the itertools solution from O(n^2) to O(n log n) by sorting:

    def all_different(*objs):
        s = sorted(objs)
        return all(x != y for x, y in zip(s[:-1], s[1:]))
    

    Here's a full implementation:

    def all_different(*objs):
        try:
            return len(frozenset(objs)) == len(objs)
        except TypeError:
            try:
                s = sorted(objs)
                return all(x != y for x, y in zip(s[:-1], s[1:]))
            except TypeError:
                return all(x != y for x, y in itertools.combinations(objs, 2))
    
    0 讨论(0)
提交回复
热议问题