使用 reduceByKey 抛出一个 int object is not subscriptable 错误

Using reduceByKey is throwing an int object is not subscriptable error

尽管该代码为我的一个朋友工作,但它给我一个“int object is not subscriptable”错误。错误出现在我尝试使用 reduceByKey 计算平均值的第 4 行。这是为什么?

nonNullRDD = marchRDD.filter(lambda row: row.journal).filter(lambda row: row.abstract)
abstractRDD = nonNullRDD.map(lambda field: (field.journal, field.abstract))
splitRDD = abstractRDD.map(lambda word: (word[0], len(word[1].split(" "))))
groupedRDD = splitRDD.reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1])).mapValues(lambda x: x[0]/x[1])

reduceByKey 函数中,您提供了一个作用于 RDD 值的 lambda 函数,RDD 是来自 len(word[1].split(" ")) 的整数。您试图对一个整数执行 x[0],这导致了您遇到的错误。

我相信 RDD 应该采用 (key, (value, 1)) 的形式,这样您的代码的第四行就会给出每个键的平均值。为了实现这一点,您可以将第三行的 lambda 函数更改为:

splitRDD = abstractRDD.map(lambda word: (word[0], (len(word[1].split(" ")), 1)))