从列表中的列表中查找公共元素

时间:2021-07-02 20:31:11

标签: python

我有一个包含更多列表的列表(这是 https://pastebin.com/BW4B9gfa 的外观)。列表的数量不是恒定的。我需要创建另一个列表,该列表仅包含主列表中所有列表中的元素。 我做了这样的东西作为原型,但它不起作用:

def common_elements(list_of_lists):
    lists = list_of_lists
    common = lists[0].intersection(lists[1].intersection(lists[2].intersection(lists[3].intersection(lists[4].intersection(lists[5])))))
return common

我也看到这样的:

A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))

但我不知道如何将它用于更多列表。

3 个答案:

答案 0 :(得分:3)

如果你有一个集合列表,你可以简单地做,要获得一个集合列表,只需执行 (lists = [set(list) for list in lists])。

lists[0].intersection(*lists)

答案 1 :(得分:1)

您需要将第一个列表转换为一个集合,以便您可以使用 intersection() 方法。

使用循环而不是硬编码列表元素的所有索引。

def common_elements(lists):
    if len(lists) == 0:
        return []

    common = set(lists[0])
    for l in lists[1:]:
        common = common.intersection(l)

    return list(common)

答案 2 :(得分:1)

使用functools.reduce()

from functools import reduce

items = [[1, 2, 4], [1, 3, 4], [1, 4, 6], [1, 4, 7, 9]]
eggs = reduce(lambda x, y: set(x) & set(y), items)
print(eggs)

输出:

{1, 4}

如果想得到中间结果,可以使用itertools.accumulate()

from itertools import accumulate

items = [[1, 2, 4, 5], [1, 3, 4, 5], [1, 4, 6], [1, 4, 7, 9]]
eggs = list(accumulate(items, func = lambda x, y: set(x) & set(y)))
print(eggs)

输出:

[[1, 2, 4, 5], {1, 4, 5}, {1, 4}, {1, 4}]
相关问题