如何合并两个数组列表(x,y,z,m),仅基于(x,y,z)排除重复项

2024-06-16 12:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张表格

list1 = list(zip(SGXm, SGYm, SGZm, Lm))
list2 = list(zip(SGXmm, SGYmm, SGZmm, Lmm))

我想合并它们,同时排除重复的(x,y,z)条目,并忽略L中的差异

list1.extend(x for x in list2 if x not in list1)

只为我的x,y,z做这个工作,但是我想保留Ls(在有选择的时候保留第一个列表)。你知道吗


Tags: in条目ziplist表格lmlmmlist2
2条回答

你得提取你需要的三元组进行比较。你知道吗

seen = set(item[:3] for item in list1)
list1.extend(item for item in list2 if item[:3] not in seen)

如果您想要排序的输出(特别是如果您已经有了排序的输入)^{}^{}很好地结合在一起。如果输入尚未排序,则需要这样做。一次串联和排序:

from operator import itemgetter

commonkey = itemgetter(0, 1, 2)
combined = sorted(list1 + list2, key=commonkey)

或者如果它们已经被排序,或者您想独立排序,您可以使用heapq.merge并避免对输入进行浅表复制:

# Explicit sort calls only necessary if inputs not already sorted
list1.sort(key=commonkey)
list2.sort(key=commonkey)

# Combine already sorted inputs with heapq.merge, avoiding intermediate lists
combined = heapq.merge(list1, list2, key=commonkey)

无论您选择哪种方法,您都可以通过对groupby的简单理解来继续操作,只需获取每个唯一组中的第一个条目,就可以只保留每个唯一键的一个副本:

# Groups neighboring entries with the same key, and we keep only the first one
uniq = [next(g) for _, g in itertools.groupby(combined, key=commonkey)]

相关问题 更多 >