使用chain()将这两个列表展平,然后使用set()和{}获取公共元素。在In [78]: from itertools import chain
In [79]: p
Out[79]:
[(‘link1/d/b/c’, ‘target1/d/b/c’),
(‘link2/a/g/c’, ‘target2/a/g/c’),
(‘linkn/b/b/f’, ‘targetn/b/b/f’)]
In [80]: q
Out[80]:
[[‘target1/d/b/c’, ‘target1’, 123, 334],
[‘targetn/b/b/f’, ‘targetn’, 23, 64],
[‘targetx/f/f/f’, ‘targetx’, 999, 888]]
In [81]: set(chain(*p)).intersection(set(chain(*q)))
Out[81]: set([‘target1/d/b/c’, ‘targetn/b/b/f’])
或者使用列表理解和短路:
^{pr2}$
或使用any():In [87]: [j for i in p for j in i if any (j==z for y in q for z in y)]
Out[87]: [‘target1/d/b/c’, ‘targetn/b/b/f’]
计时:In [93]: %timeit set(chain(*p)).intersection(set(chain(*q)))
100000 loops, best of 3: 7.38 us per loop ## winner
In [94]: %timeit [j for i in p for j in i if j in (z for y in q for z in y)]
10000 loops, best of 3: 24.9 us per loop
In [95]: %timeit [j for i in p for j in i if any (j==z for y in q for z in y)]
10000 loops, best of 3: 27.4 us per loop
In [97]: %timeit [x for x in chain(*p) if x in chain(*q)]
10000 loops, best of 3: 12.6 us per loop