问题:Python的“ in”集合运算符

in对集合的python 运算符有些困惑。

如果我有一组s与某些情况下b,是不是真的b in s意味着“ 是有一些因素xs这样b == xtrue ”?

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 in s means “is there some element x in s such that b == x is true“?


回答 0

是的,但这意味着hash(b) == hash(x),因此项的相等性不足以使它们相同。

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


回答 1

那就对了。您可以像这样在解释器中尝试:

>>> a_set = set(['a', 'b', 'c'])

>>> 'a' in a_set
True

>>>'d' in a_set
False

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

回答 2

是的,这可能意味着它,或者它可以是一个简单的迭代器。例如:作为迭代器的示例:

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

同样作为检查:

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

编辑:编辑以包括集合,而不是列表和字符串

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


回答 3

字符串虽然不是set类型,但是in在脚本验证期间具有宝贵的属性:

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

我希望这可以帮助您更好地理解in此示例的用法。

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.


回答 4

集的行为与字典不同,您需要使用诸如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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。