临摹微笑
您可以使用广度优先搜索的递归形式:def overlap(a, b) -> bool: return a[-1] >= b[0] and a[-1] < b[-1]def group(d, _c, seen): return [_c, [i if i not in seen else group(d, i, seen+[i]) for i in d if overlap(_c, i)]]r = {'5ykw.pdb': [[10, 22], [33, 40], [39, 51], [63, 71], [94, 105]]}new_data = [group(r['5ykw.pdb'], i, []) for i in r['5ykw.pdb'] if not any(overlap(c, i) for c in r['5ykw.pdb'])]final_data = [a if not b else [a[0], max(h for _, h in b)] for a, b in new_data]输出:[[10, 22], [33, 51], [63, 71], [94, 105]]这也适用于具有更多重叠的输入:r = {'5ykw.pdb':[[15, 20], [18, 21], [19, 30]]}new_data = [group(r['5ykw.pdb'], i, []) for i in r['5ykw.pdb'] if not any(overlap(c, i) for c in r['5ykw.pdb'])]final_data = [a if not b else [a[0], max(h for _, h in b)] for a, b in new_data]输出:[[15, 30]]
慕盖茨4494581
您可以使用reduce自定义merge函数来创建新列表:from functools import reducedef merge(acc, curr): if not len(acc) or acc[-1][1] < curr[0]: acc.append(curr) return acc acc[-1][1] = curr[1] # update last element in accumulator return accdata = {'5ykw.pdb': [[10, 22], [33, 40], [39, 51], [63, 71], [94, 105]]}data['5ykw.pdb'] = reduce(merge, data['5ykw.pdb'], [])print(data)# {'5ykw.pdb': [[10, 22], [33, 51], [63, 71], [94, 105]]}
紫衣仙女
你可以简单地使用这个函数“去重叠”列表:def deoverlap(lst): if not lst: return [] lst = [sorted(pair) for pair in lst] # sort pairs (leave out if not needed) lst = sorted(lst) # sort by first item (breaking ties by second item) out = [] prev = lst[0] for pair in lst[1:]: if prev[1] >= pair[0]: if prev[1] < pair[1]: prev[1] = pair[1] else: out.append(prev) prev = pair out.append(prev) return outdct = {'5ykw.pdb': [[10, 22], [33, 40], [39, 51], [63, 71], [94, 105]]}dct['5ykw.pdb'] = deoverlap(dct['5ykw.pdb'])print(dct) # prints {'5ykw.pdb': [[10, 22], [33, 51], [63, 71], [94, 105]]}这里唯一的假设是输入deoverlap()是一个可比较类型(通常是数字)的对列表,其中每对是一个长度为 2 的列表。对在内部排序,然后按第一项排序,如果前对的最大值≥当前对的最小值,则合并。如果当他们是平等的合并应该不会发生,在9日的行deoverlap()应该成为 if prev[1] > pair[0]: