查找列表中的共同要素在python [英] Finding common elements in list in python

查看:123
本文介绍了查找列表中的共同要素在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查找列表中的常见元素蟒蛇?
试想一下,如果我有一个列表如下一样
[A,B],[A,C],[B,C],[C,D],[E,F],[F,G]
我的输出必须
[A B C D]
[E,F,G]
我该怎么做?
我试过是这样的。

Finding common elements in list in python? Imagine if i have a list like follows [[a,b],[a,c],[b,c],[c,d],[e,f],[f,g]] My output must be [a,b,c,d] [e,f,g] How do i do it? What i tried is like this

for i in range(0,len(fin3)):
    for j in range(i+1,len(fin3)):
        grop = []
        grop = list(set(fin3[i]) & set(fin3[j]))
        if len(grop)>0:
            grop2 = []
            grop2.append(link[i])
            grop2.append(link[j])
            grop3.append(grop2)

在此先感谢...

Thanks in advance...

推荐答案

如果你想找到哪怕名单没有相邻的,如果在结果的顺序并不重要共同点:

If you want to find common elements even if lists are no adjacent and if the order in the result doesn't matter:

def condense_sets(sets):
    result = []
    for candidate in sets:
        for current in result:
            if candidate & current:   # found overlap
                current |= candidate  # combine (merge sets)

                # new items from candidate may create an overlap
                # between current set and the remaining result sets
                result = condense_sets(result) # merge such sets
                break
        else:  # no common elements found (or result is empty)
            result.append(candidate)
    return result

例如:

>>> data = [['a','b'], ['a','c'], ['b','c'], ['c','d'], ['e','f'], ['f','g']]
>>> map(list, condense_sets(map(set, data)))
[['a', 'c', 'b', 'd'], ['e', 'g', 'f']]

请参阅替换名单的浓缩名单列表清单,同时保持订单

这篇关于查找列表中的共同要素在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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