在python中查找列表中的公共元素

时间:2014-04-18 19:22:16

标签: python arrays list combinations

在python中查找列表中的常用元素? 想象一下,如果我有一个如下列表 [[A,B],[A,C],[B,C],并[c,d],[E,F],[F,G]] 我的输出必须是 [A B C D] [E,F,G] 我该怎么做? 我尝试的是这样的

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)

提前致谢...

4 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

data = [[1, 2], [2, 3], [4, 5]]

output = []

for item1, item2 in data:
    for item_set in output:
        if item1 in item_set or item2 in item_set:
            item_set.update((item1, item2))
            break
    else:
        output.append(set((item1, item2)))

output = map(list, output)

这给出了:

output == [[1, 2, 3], [4, 5]]

答案 1 :(得分:1)

如果你想找到共同元素,即使列表不相邻,结果中的顺序也不重要:

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']]

请参阅Replace list of list with “condensed” list of list while maintaining order

答案 2 :(得分:0)

正如上面的评论中所指出的,看起来您想要进行整合。

以下是我根据上述评论中的链接代码改编的解决方案。

def consolidate(seq):
    if len(seq) < 2:
        return seq
    result, tail = [seq[0]], consolidate(seq[1:])
    for item in tail:
        if result[0].intersection(item):
            result[0].update(item)
        else:
            result.append(item)
    return result

def main():
    sets = [set(pair) for pair in [['a','b'],['a','c'],['b','c'],['c','d'],['e','f'],['f','g']]]
    print("Input: {0}".format(sets))
    result = consolidate(sets)
    print("Result: {0}".format(result))

if __name__ == '__main__':
    main()

示例输出:

Input: [set(['a', 'b']), set(['a', 'c']), set(['c', 'b']), set(['c', 'd']), set(['e', 'f']), set(['g', 'f'])]
Result: [set(['a', 'c', 'b', 'd']), set(['e', 'g', 'f'])]

答案 3 :(得分:0)

另一种方法,看起来像(有效) - O(n ^ 2)其中n =项目数。它不太优雅,但它是正确的。如果为命名参数True提供值return_sets,则以下函数返回一组(hashable)frozensets,否则返回列表列表(默认情况下,因为您的问题表明&#39;你真正想要的东西):

def create_equivalence_classes(relation, return_sets=False):
    eq_class = {}
    for x, y in relation:
        # Use tuples of x, y in case either is a string of length > 1 (iterable),
        # and so that elements x, y can be noniterables such as ints.
        eq_class_x = eq_class.get(x, frozenset( (x,) ))
        eq_class_y = eq_class.get(y, frozenset( (y,) ))
        join = eq_class_x.union(eq_class_y)
        for u in eq_class_x:
            eq_class[u] = join
        for v in eq_class_y:
            eq_class[v] = join
    set_of_eq_classes = set(eq_class.values())
    if return_sets:
        return set_of_eq_classes
    else:
        return list(map(list, set_of_eq_classes))

用法:

>>> data = [['a','b'], ['a','c'], ['b','c'], ['c','d'], ['e','f'], ['f','g']]
>>> print(create_equivalence_classes(data))
[['d', 'c', 'b', 'a'], ['g', 'f', 'e']]
>>> print(create_equivalence_classes(data, return_sets=False))
{frozenset({'d', 'c', 'b', 'a'}), frozenset({'g', 'f', 'e'})}

>>> data1 = [['aa','bb'], ['bb','cc'], ['bb','dd'], ['fff','ggg'], ['ggg','hhh']]
>>> print(create_equivalence_classes(data1))
[['bb', 'aa', 'dd', 'cc'], ['hhh', 'fff', 'ggg']]

>>> data2 = [[0,1], [2,3], [0,2], [16, 17], [21, 21], [18, 16]]
>>> print(create_equivalence_classes(data2))
[[21], [0, 1, 2, 3], [16, 17, 18]]
相关问题