“add to set” returns a boolean in java - what about python?

前端 未结 5 734
小蘑菇
小蘑菇 2021-01-11 17:24

In Java I like to use the Boolean value returned by an \"add to the set\" operation to test whether the element was already present in the set:

if (set.add(\         


        
5条回答
  •  走了就别回头了
    2021-01-11 18:00

    For the built-in set type, add() always gives back None, but there is nothing to prevent you from using a "smarter" subclass:

    class sset(set):
        """return True if on add if an object was really added (and not in yet)"""
        def add(self, val):
            if val in self:
                return True
            set.add(self, val)
            return False
    

    This allows you to write:

    s = sset()
    if s.add('1'):
        print('try 1')
    if s.add('1'):
        print('try 2')
    

    and get try 2 printed when run.

    This prevents repeated multiple lines of code like @brandizzi's which can easily contain inefficiencies:

    z = set()
    was_here = y not in z
    z.add(y)
    if was_here: # If the object was not in the list yet...
        print something
    

    which is inefficient as y is added even if it is already in. It should be something like:

    z = set()
    was_here = y not in z
    if not was_here:
        z.add(y)
    else: # If the object was not in the list yet...
        print something
    

    With sset() this can be reduced to:

    z = sset()
    if z.add(y): # If the object was not in the list yet...
        print something
    

提交回复
热议问题