如何将列表与列表列表中的公共元素合并?

我正在尝试合并具有公共元素的列表列表中的所有列表。我有一些工作代码。但是,它似乎打破了这个例子:


def merge_subs(lst_of_lsts):

    res = []

    for row in lst_of_lsts:

        for i, resrow in enumerate(res):

            if row[0]==resrow[0]:

                res[i] += row[1:]

                break

            else:

                res.append(sorted(row))

    return sorted(res)

输入是:


merge_subs([[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]])

我的结果是:


[[0, 2, 4, 6], [1, 3, 5, 7], [3, 5, 7]]

但我应该得到:


[[0, 2, 4, 6], [1, 3, 5, 7]]


元芳怎么了
浏览 228回答 2
2回答

交互式爱情

您需要使用递归:def group(d, _start, _c = [], _seen = [], _used=[]):  r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]  if not r:    yield set(_c)    for i in d:      if i != _start and i not in _used:         yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])  else:    yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]result = list(map(list, {tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i}))输出:[[0, 2, 4, 6], [1, 3, 5, 7]]

吃鸡游戏

这个问题可以使用递归解决,特别是尾递归:def merge(lists, results=None):    if results is None:        results = []    if not lists:        return results    first = lists[0]    merged = []    output = []    for li in lists[1:]:        for i in first:            if i in li:                merged = merged + li                break        else:            output.append(li)    merged = merged + first    results.append(list(set(merged)))    return merge(output, results)结果如下所示:>>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]>>> merge(lists)[[1, 3, 5, 7], [0, 2, 4, 6]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python