>>> assert 1 in [1, 2, 3] # lists >>> assert 4 not in [1, 2, 3] >>> assert 1 in {1, 2, 3} # sets >>> assert 4 not in {1, 2, 3} >>> assert 1 in (1, 2, 3) # tuples >>> assert 4 not in (1, 2, 3)
而dict的成员关系判断,则是判断key:
>>> d = {1: 'foo', 2: 'bar', 3: 'qux'} >>> assert 1 in d >>> assert 4 not in d >>> assert 'foo' not in d # 'foo' is not a _key_ in the dict
>>> s = 'foobar' >>> assert 'b' in s >>> assert 'x' not in s >>> assert 'foo' in s # a string "contains" all its substrings
classFoo:def__init__(self,item):self.item = itemdef__contains__(self,*args):print("membership testing...")return args[0]in self.itemf = Foo([1,2,3,4]) print(1in f)# 成员关系判断,调用了__containers__方法 print(100in f)# 同上 ---for ele in f:# 迭代,调用了__iter__方法。因为没有定义,因此是不可迭代对象print(ele)
输出:
membership testing... True membership testing... False -- Traceback (most recent call last):File "E:/PyProject/test02.py", line 14, in for ele in f: TypeError: 'Foo' object is not iterable
是容器,支持成员关系判断,是可迭代对象:
classFoo:def__init__(self,item):self.item = itemself.iter=iter(item)def__contains__(self,*args):print("membership testing...")return args[0]in self.itemdef__iter__(self):print('Ready to iter...')return self.iterf = Foo([1,2,3,4])for ele in f:# 是可迭代对象,因此可迭代print(ele)
>>> numbers = [1, 2, 3, 4, 5, 6] >>> [x * x for x in numbers] [1, 4, 9, 16, 25, 36]>>> {x * x for x in numbers} {1, 4, 36, 9, 16, 25}>>> {x: x * x for x in numbers} {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
生成器表达式:
>>> a = (x*x for x in range(10)) >>> a at 0x401f08> >>> sum(a) ## 已经消费完a里面的值 285 >>> a = (x*x for x in range(10)) >>> next(a) ## 开始消费 0 >>> list(a) [1,2,3,4,5,6,7,8,9]