比较两个列表的元素 [英] compare elements of two lists
问题描述
A = [a1, a2, a3...] #a1<a2<a3...
B = [b1, b2...] #b1<b2<b3...
A和B不相交.我不知道元素的数量和它们在A/B中的价值是否提前.我想比较列表和删除元素iff中的元素的值:
A and B are disjoint. are I do not know the number of elements and the value of them in A/B in advance. I want to compare the value of the elements in both list and delete elements iff:
delete a[i+1] if there is no b[j] such that a[i]<b[j]<a[i+1]
delete b[i+1] if there is no a[j] such that b[i]<a[j]<b[i+1]
最后,我想分隔列表,而不是A和B的组合.
At the end, I want to separate list, not a combination of A and B.
例如,如果A[0] < B[0]
,则A = [1,10,40],B = [15,30].首先比较A[1]
和B[0]
.删除10
,因为B中没有元素在1到15之间.
然后删除15
,因为15和30之间不再存在任何元素.输出应该是:如果尝试对新的2个列表的元素进行排序,则应该为A[0]<B[0]<A[1]<B[1]<...
For example, If A[0] < B[0]
, A = [1, 10, 40], B = [15, 30]. Compare A[1]
and B[0]
first. Delete 10
because no element in B are in between 1 and 15.
Then delete 15
since no element exist anymore btw 15 and 30. The output should be: if you try to order the elements of the new 2 lists, it should be A[0]<B[0]<A[1]<B[1]<...
如果是A[0] > B[0]
,反之亦然.
推荐答案
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
返回:
a = [1, 40]
b = [15]
和
a = [3, 4, 6, 7, 8, 9]
b = [1, 2, 5, 10]
它返回[3, 6]
和[1, 5, 10]
.
编辑:另一种可能性:
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
这篇关于比较两个列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!