关于将相同编号的子列表链接在一起的python [英] python about linking sublist with same number together

查看:103
本文介绍了关于将相同编号的子列表链接在一起的python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将具有相同元素的子列表分组在一起 例如:

I need to group sublists with the same elements together For example:

list1 =[[1, 0], [2, 1], [30, 32]]

将链接[1, 0][2, 1]在一起,因为它们都包含1,并且两者将合并为[0, 1, 2]

would link [1, 0] and [2, 1] together since they both contain 1 and those two would combine into [0, 1, 2]

因此,链接后,新列表应类似于:

So after linking, the new list should be like:

new_list1 = [[1, 0, 2], [30, 32]]

IE:子列表中不应有相同的数字,顺序也不重要.

IE: there shouldn't be same number inside a sub-list and order is not important.

一个更长的例子:

list2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]

链接后为

new_list2 = [[2, 3, 4], [6, 5, 7, 8], [13, 14], [30, 32]]

那么如何以一般的方式完成呢?

So how can this be done in a general way?

推荐答案

要以常规方式对子列表进行分组,您可以:

To group the sublists in a general way you can:

def linking_sublists(lists):
    index = {}
    sets = []
    for l in lists:
        found = None
        for i in l:
            if i in index:
                # this list has an element we have already seen
                if found:
                    # combine two sets
                    to_remove = index[i]
                    if found != to_remove:
                        for j in index[i]:
                            found.add(j)
                            index[j] = found
                        to_remove.clear()
                else:
                    found = index[i]

        if found is not None:
            s = found
            for i in l:
                s.add(i)
        else:
            s = set(l)
            sets.append(s)
        for i in l:
            index[i] = s

    return [list(sorted(s)) for s in sets if s]

方法:

此函数使用集合和索引 dict 来将具有匹配元素的任何列表归为一组,并跟踪 .

list_2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]
print(linking_sublists(list_2))

list_3 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [30, 32], [4, 5], [3, 4]]
print(linking_sublists(list_3))

结果:

[[2, 3, 4], [5, 6, 7, 8], [13, 14], [30, 32]]
[[2, 3, 4, 5, 6, 7, 8], [30, 32]]

这篇关于关于将相同编号的子列表链接在一起的python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆