08 in

回顾

  • index() 的索引值超出范围时会抛出异常
>>> [0, 1, 2, 3, 4].index(6)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    [0, 1, 2, 3, 4].index(6)
ValueError: 6 is not in list
>>> 

in

  • inindex() 搭配可以防止上述的异常
>>> a = [0, 1, 2, 3, 4]
>>> if 6 in a:
    print(a.index(6))
else:
    print("not found")

    
not found
>>> 

not in

>>> 6 not in [0, 1, 2, 3, 4]
True
>>> 

补充

  • in, not in 只能判断一层关系
>>> 3 in [0, 1, 2, [3, 4, 5]]
False
>>> 
  • 两层的解决办法
>>> for e in a:
    if type(e) is list:
        print(3 in e)
    elif e == 3:
        print(True)

        
True
>>> 
原文地址:https://www.cnblogs.com/yorkyu/p/10316064.html