Python 的“ in”集运算符

我对用于集合的 pythonin操作符有点困惑。

如果我有一个集合 s和一些实例 b,那么 b in s真的意味着“ 在 ABC0中是否有一些元素 ABC3使得 ABC5是 true”吗?

355648 次浏览

是的,但是 还有意味着 hash(b) == hash(x),所以项目的相等性不足以使它们相同。

没错,你可以这样在翻译中试试:

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


>>> 'a' in a_set
True


>>>'d' in a_set
False

字符串虽然不是 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的用法。

是的,它可以是这个意思,也可以是一个简单的迭代器。例如: 例如迭代器:

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')

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

集合的行为与 dicts 不同,您需要使用集合操作,比如 issub () :

>>> 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

List 的 _ _ include _ _ 方法使用其元素的 好吧方法。而 集合的 _ _ 包含 _ _使用 哈希。看一下下面的例子,我希望能够明确地说明:

class Salary:
"""An employee receives one salary for each job he has."""


def __init__(self, value, job, employee):
self.value = value
self.job = job
self.employee = employee


def __repr__(self):
return f"{self.employee} works as {self.job} and earns {self.value}"


def __eq__(self, other):
"""A salary is equal to another if value is equal."""
return self.value == other.value


def __hash__(self):
"""A salary can be identified with the couple employee-job."""
return hash(self.employee) + hash(self.job)


alice = 'Alice'
bob = 'Bob'
engineer = 'engineer'
teacher = 'teacher'


alice_engineer = Salary(10, engineer, alice)
alice_teacher = Salary(8, teacher, alice)
bob_engineer = Salary(10, engineer, bob)


print(alice_engineer == alice_teacher)
print(alice_engineer == bob_engineer, '\n')


print(alice_engineer is alice_engineer)
print(alice_engineer is alice_teacher)
print(alice_engineer is bob_engineer, '\n')


alice_jobs = set([alice_engineer, alice_teacher])
print(alice_jobs)
print(bob_engineer in alice_jobs)  # IMPORTANT
print(bob_engineer in list(alice_jobs))  # IMPORTANT

控制台打印:

False
True


True
False
False


{Alice works as teacher and earns 8, Alice works as engineer and earns 10}
False
True