您可以使用带有itertools.combinations 的字典:
from itertools import combinations, chain
L = [['a', ['a1', 'a2', 'a3']], ['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]]
d = dict(L)
res = {comb: list(chain.from_iterable(map(d.__getitem__, comb))) \
for comb in combinations(d, 2)}
结果:
{('a', 'b'): ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'],
('a', 'c'): ['a1', 'a2', 'a3', 'c1', 'c2', 'c3'],
('b', 'c'): ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']}
或者,如果您更喜欢嵌套列表:
res_lst = [[list(comb), list(chain.from_iterable(map(d.__getitem__, comb)))] \
for comb in combinations(d, 2)]
# [[['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']],
# [['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3']],
# [['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]]
在这两种情况下,想法都是减少 Python 级 for 循环的数量。