假设您的 L1 子列表中可能有多个“控制”项。
我会用set() http://docs.python.org/py3k/library/stdtypes.html#set-types-set-frozenset and itertools.product() http://docs.python.org/py3k/library/itertools.html#itertools.product:
from itertools import product
def generate_edges(iterable, control):
edges = []
control_set = set(control)
for e in iterable:
e_set = set(e)
common = e_set & control_set
to_pair = e_set - common
edges.extend(product(to_pair, common))
return edges
Example:
>>> L1 = [["cat","dog","apple"],
... ["orange","green","red"],
... ["hand","cat","red"]]
>>> L2 = ["cat","red"]
>>> generate_edges(L1, L2)
[('apple', 'cat'),
('dog', 'cat'),
('orange', 'red'),
('green', 'red'),
('hand', 'red'),
('hand', 'cat')]