# testing列表是否共享Python中的任何项目

``In [78]: a = [1, 2, 3, 4, 5] In [79]: b = [8, 7, 6] In [80]: c = [8, 7, 6, 5] In [81]: def lists_overlap(a, b): ....: for i in a: ....: if i in b: ....: return True ....: return False ....: In [82]: lists_overlap(a, b) Out[82]: False In [83]: lists_overlap(a, c) Out[83]: True In [84]: def lists_overlap2(a, b): ....: return len(set(a).intersection(set(b))) > 0 ....:` `

` `bool(set(a) & set(b))` `

` `any(i in a for i in b)` `

` `a = set(a); any(i in a for i in b)` `

` `not set(a).isdisjoint(b)` `

` `from timeit import timeit >>> timeit('bool(set(a) & set(b))', setup="a=list(range(1000));b=list(range(1000))", number=100000) 26.077727576019242 >>> timeit('any(i in a for i in b)', setup="a=list(range(1000));b=list(range(1000))", number=100000) 0.16220548999262974` `

` `>>> timeit('any(i in a for i in b)', setup="a=list(range(1000));b=[x+998 for x in range(999,0,-1)]", number=1000)) 13.739536046981812 >>> timeit('bool(set(a) & set(b))', setup="a=list(range(1000));b=[x+998 for x in range(999,0,-1)]", number=1000)) 0.08102107048034668` `

• 如果列表非常小（<10个元素）， `not set(a).isdisjoint(b)`总是最快的。
• 如果列表中的元素被sorting或者具有可以利用的规则结构，那么生成器expression式`any(i in a for i in b)`是大列表中最快的;
• `not set(a).isdisjoint(b)`testing集合交集，总是比`bool(set(a) & set(b))`快。
• 混合“遍历列表，testing集” `a = set(a); any(i in a for i in b)` `a = set(a); any(i in a for i in b)`一般比其他方法慢。
• 在没有共享元素的情况下，生成器expression式和混合器比其他两种方法慢得多。

` `def lists_overlap3(a, b): return bool(set(a) & set(b))` `

` `def lists_overlap(a, b): sb = set(b) return any(el in sb for el in a)` `

` `lists_overlap([3,4,5], [1,2,3])` `

` `def lists_overlap(a, b): sb = set(b) return any(itertools.imap(sb.__contains__, a))` `

` `any([item in a for item in b])` `

` `return not frozenset(a).isdisjoint(frozenset(b))` `

` `def list_overlap(a,b): return any(i for i in a if i in b)` `

` `return any(i in b for i in a)` `

`len(set(a+b+c))==len(a+b+c)`返回True，如果没有重叠。

` `>>> timeit('bool(set(a) & set(b))', setup="a=list(range(10000)); b=[x+9999 for x in range(10000)]", number=100000) 100.91506409645081 >>> timeit('any(i in a for i in b)', setup="a=list(range(10000)); b=[x+9999 for x in range(10000)]", number=100000) 19.746716022491455 >>> timeit('any(i in a for i in b)', setup="a= set(range(10000)); b=[x+9999 for x in range(10000)]", number=100000) 0.092626094818115234` `

` `>>> timeit('bool(set(a) & set(b))', setup="a=list(range(10000)); b=list(range(10000))", number=100000) 154.69790101051331 >>> timeit('any(i in a for i in b)', setup="a=list(range(10000)); b=list(range(10000))", number=100000) 0.082653045654296875 >>> timeit('any(i in a for i in b)', setup="a= set(range(10000)); b=list(range(10000))", number=100000) 0.08434605598449707` `

` `any(map(lambda x: x in a, b))` `

` `map(lambda x: x in a, b)` `