Python 列表,保留列表的所有子列表中的所有值

Python list, keep all value present in all sublist of a list

我需要找到更大列表的所有子列表中存在的所有值(它们都是 ID)

我尝试的是首先获取所有列表中存在的所有唯一值,然后他们测试每个值,但这在大列表上非常慢

l1 = ["a", "b", "c", "d", "e", "f"]
l2 = ["b", "c", "e", "f", "g"]
l3 = [ "b", "c", "d", "e", "f", "h"]
LL = [l1, l2, l3]
LL
unique_ids = set(x for l in LL for x in l)

filter_id = []
lenList = len(LL)
for id in unique_ids:
    if sum(id in item for item in LL) == lenList:
        filter_id.append(id)

我怎样才能加快搜索速度?

创建一组在所有列表中找到的元素:

from itertools import chain
{elem for elem in chain(l1, l2, l3) if elem in l1 and elem in l2 and elem in l3}
# {'f', 'c', 'e', 'b'}

I need to find all value that are present in all sublist of a larger list (they are all ids).

如果我们将这些子列表合并为一个列表,我们的 "values that are present in all sublists" 将恰好出现 len(LL) 次(在本例中为 3 次)。 ;)

这可以使用计数器在一行中完成:

from collections import Counter

result = [key for key, value in Counter(elem for sub_list in LL for elem in set(sub_list)).items() if value == len(LL)]

解释:

  • set(sub_list) - 我们删除了子列表中意外的重复项,以免弄乱我们的计数
  • (elem for sub_list in LL for elem in set(sub_list)) - 将其展平为单个可迭代对象
  • Counter - returns 包含每个元素在可迭代对象中出现的次数的字典
  • dict.items() 成对获取键和值
  • if value == len(LL) - 过滤每个子列表中存在的键

编辑:为了提高可读性,什么是什么:

result = [key 
          for key, value in Counter(elem 
                                    for sub_list in LL 
                                    for elem in set(sub_list)
                                   ).items() 
          if value == len(LL)]