Python使用交集合并多个列表 [英] Python merge multiple list with intersection

查看:89
本文介绍了Python使用交集合并多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python:基于交集的简单列表合并

Possible Duplicate:
Python: simple list merging based on intersections

我有多个列表:

 list=[[1,2,3],[3,5,6],[8,9,10],[11,12,13]]

是否有一种灵巧,快速的方法来获取至少具有一个交集的所有子列表.在我的示例中,我希望代码返回

Is there a smart and fast way to get all the sublists with at least one intersection. In my example I want that the code return

 result=[[1,2,3,5,6],[8,9,10],[11,12,13]]

推荐答案

这可行,但可能不是很优雅:

This works, but maybe isn't very elegant:

def merge_lists(l):
        s=map(set, l)
        i, n=0, len(s)
        while i < n-1:
                for j in xrange(i+1, n):
                        if s[i].intersection(s[j]):
                                s[i].update(s[j])
                                del s[j]
                                n-=1
                                break
                else:
                        i+=1
        return [sorted(i) for i in s]

这篇关于Python使用交集合并多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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