a = [1, 10, 40]
b = [15, 30]
srcs = [a, b]
dsts = [[], []]
prev_which = -1
while all(srcs):
which = int(srcs[0][0] > srcs[1][0])
elem = srcs[which].pop(0)
if prev_which != which:
dsts[which].append(elem)
prev_which = which
for src, dst in zip(srcs,dsts):
if src:
dst.append(src.pop(0))
a, b = dsts
returns:
a = [1, 40]
b = [15]
and for
a = [3, 4, 6, 7, 8, 9]
b = [1, 2, 5, 10]
它返回[3, 6]
and [1, 5, 10]
.
EDIT: 另一种可能:
import itertools as it
import operator as op
a = [3, 4, 6, 7, 8, 9]
b = [1, 2, 5, 10]
srcs = [a, b]
dsts = [[], []]
for which, elems in it.groupby(sorted((x, i) for i in (0,1) for x in srcs[i]), key=op.itemgetter(1)):
dsts[which].append(next(elems)[0])
a, b = dsts