Python中嵌套for循环的一个问题

这个序列处理中的很基础但又很重要的问题,比如说, 从第一个列表中找第二个列表中存在的项

items = [(1,2), 3, "book", 3.14]
tests = [100, (1,2)]

通常做法

>>> items = [(1,2), 3, "book", 3.14]
>>> tests = [100, (1,2)]
>>> for key in tests:                       # 先遍历第二个列表
...     for item in items:                  # 再遍历第一个列表
...         if key == item:                 # 做出条件判断
...             print(key, "WAS FOUND!")
...             break                       # 找到终止小循环
...     else:                               # 未找到处理方式
...         print(key, "NOT FOUND!")
...
100 NOT FOUND!
(1, 2) WAS FOUND!
>>>

改用in运算符来测试成员关系

>>> items = [(1,2), 3, "book", 3.14]
>>> tests = [100, (1,2)]
>>> for key in tests:
...     if key in items:
...         print(key, "WAS FOUND!")
...     else:
...         print(key, "NOT FOUND!")
...
100 NOT FOUND!
(1, 2) WAS FOUND!
>>>

备注: 从简洁度和性能及代码结构来考虑,第二种方式,无疑要好的多。

你可能感兴趣的:(【编程语言】,【系统运维】,【系统测试】,in运算符,嵌套for循环)