Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查一个元素是否正好存在于一组4个列表中的3个列表中_Python - Fatal编程技术网

Python 如何检查一个元素是否正好存在于一组4个列表中的3个列表中

Python 如何检查一个元素是否正好存在于一组4个列表中的3个列表中,python,Python,我有4个列表,每个列表有几个元素。我正在尝试制作另外4个列表,这些列表将告诉我们每个特定元素显示了多少个列表。因此,我的一个列表将告诉我所有4个原始列表中的元素。另一个会告诉我哪些元素在4个列表中的3个列表中。一个元素在列表中出现多少次并不重要,重要的是它在多少个列表中 这对于很长的if语句是可行的,a-la if ((element in list1) and (element in list2) and \ (element in list3) and not (element in lis

我有4个列表,每个列表有几个元素。我正在尝试制作另外4个列表,这些列表将告诉我们每个特定元素显示了多少个列表。因此,我的一个列表将告诉我所有4个原始列表中的元素。另一个会告诉我哪些元素在4个列表中的3个列表中。一个元素在列表中出现多少次并不重要,重要的是它在多少个列表中

这对于很长的if语句是可行的,a-la

if ((element in list1) and (element in list2) and \
(element in list3) and not (element in list4)) or...
使用各种组合,但我想要更干净,可能更快的

这大概就是我正在处理的问题:

list1 = [1, 2, 4, 6, 8]
list2 = [1, 2, 4, 7, 8]
list3 = [1, 2, 5, 7, 8]
list4 = [1, 3, 5, 7, 8]
所以你可以看到1和8出现在每个列表中,2出现在三个列表中,以此类推

这就是我想要的输出:

in_all_4_lists = [1, 8]
in_3_lists = [2, 7]
in_2_lists = [4, 5]
in_1_list  = [3, 6]
如果原始列表中有任何重复项,则无所谓,只要元素存在即可


进行此操作的最佳方法是什么?

使用
collections.Counter
获取列表中出现的次数,然后进行累加,例如:

counts = Counter(el for lst in (list1, list2, list3, list4) for el in set(lst))
这给了你:

Counter({1: 4, 2: 3, 4: 2, 6: 1, 8: 4, 7: 3, 5: 2, 3: 1})
然后:

然后
d
将是:

{4: [1, 8], 3: [2, 7], 2: [4, 5], 1: [6, 3]}

您可以轻松使用和的组合,如下所示:

from collections import Counter

l1 = ['a', 'b', 'c']
l2 = ['a', 'a', 'd']
l3 = ['a', 'd', 'e']
l4 = ['a', 'b', 'a']

c = Counter(set(l1))
c.update(set(l2))
c.update(set(l3))
c.update(set(l4))

print(c)  # >> Counter({'a': 4, 'b': 2, 'd': 2, 'c': 1, 'e': 1})
如果你真的想在最后使用单独的列表,有一种可能是使用,这在这里不是最好的,但是你说你的列表很小,所以…:

   r1 = [item for item, count in c.items() if count == 1]
   r2 = [item for item, count in c.items() if count == 2]
   r3 = [item for item, count in c.items() if count == 3]
   r4 = [item for item, count in c.items() if count == 4]
   r1 = [item for item, count in c.items() if count == 1]
   r2 = [item for item, count in c.items() if count == 2]
   r3 = [item for item, count in c.items() if count == 3]
   r4 = [item for item, count in c.items() if count == 4]