这是一个itertools.product、itertools.groupby 方法:
>>> import random
>>> import itertools
>>>
# create random lists
>>> x, y, z = map(list, map(range, 3*(20,)))
>>> any(map(random.shuffle, (x, y, z)))
False
>>> x, y, z = x[:10], y[:10], z[:10]
>>>
# choose a sum
>>> sum_ = 40
>>>
# compute and sort all sums of the first two
>>> xy = sorted(itertools.product(x, y), key=sum)
# and group by these sums
>>> xy = {k: list(v) for k, v in itertools.groupby(xy, sum)}
# use this to look up the matching x, y if any for each z
>>> xyz = [(a, b, c) for c in z for a, b in xy.get(sum_-c, ())]
>>> xyz
[(18, 4, 18), (16, 6, 18), (6, 16, 18), (4, 18, 18), (5, 18, 17), (7, 16, 17), (18, 5, 17), (16, 7, 17), (16, 16, 8), (7, 18, 15), (18, 7, 15), (16, 9, 15), (5, 16, 19), (11, 10, 19), (18, 3, 19), (16, 5, 19), (18, 16, 6), (16, 18, 6), (11, 18, 11), (11, 16, 13), (18, 9, 13)]
>>>
# validate
>>> set(map(sum, xyz))
{40}