将一个列表中的两个子列表合并为一个子列表python

我有一个字典,其中有一个列表,该列表将成对的数字作为子列表,我试图检查子列表之间是否存在重叠。

{'5ykw.pdb': [[10, 22], [33, 40], [39, 51], [63, 71], [94, 105]]}

[33, 40] 和 [39, 51] 之间有重叠,所以我想合并它们来制作:

{'5ykw.pdb': [[10, 22], [33, 51], [63, 71], [94, 105]]}


繁星coding
浏览 322回答 3
3回答

临摹微笑

您可以使用广度优先搜索的递归形式:def overlap(a, b) -> bool:&nbsp; return a[-1] >= b[0] and a[-1] < b[-1]def group(d, _c, seen):&nbsp; &nbsp;return [_c,&nbsp;&nbsp; &nbsp; &nbsp;[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):&nbsp; &nbsp; if not len(acc) or acc[-1][1] < curr[0]:&nbsp; &nbsp; &nbsp; &nbsp; acc.append(curr)&nbsp; &nbsp; &nbsp; &nbsp; return acc&nbsp; &nbsp; acc[-1][1] = curr[1] # update last element in accumulator&nbsp; &nbsp; 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):&nbsp; &nbsp; if not lst:&nbsp; &nbsp; &nbsp; &nbsp; return []&nbsp; &nbsp; lst = [sorted(pair) for pair in lst]&nbsp; # sort pairs (leave out if not needed)&nbsp; &nbsp; lst = sorted(lst)&nbsp; # sort by first item (breaking ties by second item)&nbsp; &nbsp; out = []&nbsp; &nbsp; prev = lst[0]&nbsp; &nbsp; for pair in lst[1:]:&nbsp; &nbsp; &nbsp; &nbsp; if prev[1] >= pair[0]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if prev[1] < pair[1]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prev[1] = pair[1]&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out.append(prev)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prev = pair&nbsp; &nbsp; out.append(prev)&nbsp; &nbsp; return outdct = {'5ykw.pdb': [[10, 22], [33, 40], [39, 51], [63, 71], [94, 105]]}dct['5ykw.pdb'] = deoverlap(dct['5ykw.pdb'])print(dct)&nbsp; # prints {'5ykw.pdb': [[10, 22], [33, 51], [63, 71], [94, 105]]}这里唯一的假设是输入deoverlap()是一个可比较类型(通常是数字)的对列表,其中每对是一个长度为 2 的列表。对在内部排序,然后按第一项排序,如果前对的最大值≥当前对的最小值,则合并。如果当他们是平等的合并应该不会发生,在9日的行deoverlap()应该成为&nbsp; &nbsp; &nbsp; &nbsp; if prev[1] > pair[0]:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python