2024-06-16 12:35:18 发布
网友
我有两张表格
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(在有选择的时候保留第一个列表)。你知道吗
你得提取你需要的三元组进行比较。你知道吗
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并避免对输入进行浅表复制:
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的简单理解来继续操作,只需获取每个唯一组中的第一个条目,就可以只保留每个唯一键的一个副本:
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)]
你得提取你需要的三元组进行比较。你知道吗
如果您想要排序的输出(特别是如果您已经有了排序的输入)^{} 和^{} 很好地结合在一起。如果输入尚未排序,则需要这样做。一次串联和排序:
或者如果它们已经被排序,或者您想独立排序,您可以使用
heapq.merge
并避免对输入进行浅表复制:无论您选择哪种方法,您都可以通过对
groupby
的简单理解来继续操作,只需获取每个唯一组中的第一个条目,就可以只保留每个唯一键的一个副本:相关问题 更多 >
编程相关推荐