使用 mapreduce 计算嵌套列表中包含特定元素的列表的数量

Count the number of lists containing specific element in a nested list with mapreduce

我有一个包含字符串的列表列表,我想计算每个元素出现的列表数量:

list_of_lists = [["dog", "cow"], ["dragon", "ox", "cow"], ["fox", "cow", "dog"]]

因此,cow 出现在 3 个列表中,dog 出现在 2 个列表中,依此类推

对于这么小的数据集,我通常会这样做:

from collections import Counter
from itertools import chain
count = Counter(chain.from_iterable(set(x) for x in list_of_lists))

因此:

print(count["dog"])
2

但是,我想使用 PySpark 和 MapReduce 对大型数据集执行此操作,以便对于列表列表中的每个元素,我将具有上述计数器值:

    [("dog", 2),
    ("cow", 3),
    ("dragon", 1),
    ("ox", 1),
    ("fox", 1)]

等等

我正在尝试这样的事情:

list_of_lists = sc.parallelize(list_of_lists)
list_occurencies = list_of_lists.map(lambda x: x, count[x])

没有效果

使用 flatMap 展平嵌套数组,然后 reduceByKey 获取列表中每个单词的计数:

list_of_lists = sc.parallelize(list_of_lists)

list_of_lists = list_of_lists.flatMap(lambda x: set(x))\
    .map(lambda x: (x, 1))\
    .reduceByKey(lambda a, b: a + b)

print(list_of_lists.collect())
# [('fox', 1), ('dragon', 1), ('ox', 1), ('dog', 2), ('cow', 3)]