Python's “in” set operator

前端 未结 5 1137
刺人心
刺人心 2020-12-25 09:24

I\'m a little confused about the python in operator for sets.

If I have a set s and some instance b, is it true that b i

相关标签:
5条回答
  • 2020-12-25 09:44

    Strings, though they are not set types, have a valuable in property during validation in scripts:

    yn = input("Are you sure you want to do this? ")
    if yn in "yes":
        #accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
        return True
    return False
    

    I hope this helps you better understand the use of in with this example.

    0 讨论(0)
  • 2020-12-25 09:45

    Yes it can mean so, or it can be a simple iterator. For example: Example as iterator:

    a=set(['1','2','3'])
    for x in a:
     print ('This set contains the value ' + x)
    

    Similarly as a check:

    a=set('ILovePython')
    if 'I' in a:
     print ('There is an "I" in here')
    

    edited: edited to include sets rather than lists and strings

    0 讨论(0)
  • 2020-12-25 09:52

    Sets behave different than dicts, you need to use set operations like issubset():

    >>> k
    {'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
    >>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
    True
    >>> set('ip,port,pw'.split(',')) in set(k.keys())
    False
    
    0 讨论(0)
  • 2020-12-25 09:54

    Yes, but it also means hash(b) == hash(x), so equality of the items isn't enough to make them the same.

    0 讨论(0)
  • 2020-12-25 09:55

    That's right. You could try it in the interpreter like this:

    >>> a_set = set(['a', 'b', 'c'])
    
    >>> 'a' in a_set
    True
    
    >>>'d' in a_set
    False
    
    0 讨论(0)
提交回复
热议问题