gpt4 book ai didi

python - 使用 reducebykey 错误 : int object is unsubscriptable

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:57 25 4
gpt4 key购买 nike

我在执行以下脚本时遇到错误“int object is unsubscriptable”:

element.reduceByKey( lambda x , y : x[1]+y[1])

with element是一个key-value RDD,value是一个tuple。输入示例:

(A, (toto , 10))
(A, (titi , 30))
(5, (tata, 10))
(A, (toto, 10))

我知道 reduceByKey 函数采用 (K,V) 元组并对所有值应用函数以获得 reduce 的最终结果。就像 ReduceByKey Apache 中给出的例子一样.

有什么帮助吗?

最佳答案

这里有一个例子可以说明发生了什么。

让我们考虑一下当您使用某个函数 f 在列表上调用 reduce 时会发生什么:

reduce(f, [a,b,c]) = f(f(a,b),c)

如果我们以您的示例为例,f = lambda u, v: u[1] + v[1],则上述表达式分解为:

reduce(f, [a,b,c]) = f(f(a,b),c) = f(a[1]+b[1],c)

但是 a[1] + b[1] 是一个整数,所以没有 __getitem__ 方法,因此你的错误。

一般而言,更好的方法(如下所示)是使用map() 首先以您想要的格式提取数据,然后应用reduceByKey().


包含您的数据的 MCVE

element = sc.parallelize(
[
('A', ('toto' , 10)),
('A', ('titi' , 30)),
('5', ('tata', 10)),
('A', ('toto', 10))
]
)

几乎可以使用更复杂的 reduce 函数获得所需的输出:

def add_tuple_values(a, b):
try:
u = a[1]
except:
u = a
try:
v = b[1]
except:
v = b
return u + v

print(element.reduceByKey(add_tuple_values).collect())

除了这会导致:

[('A', 50), ('5', ('tata', 10))]

为什么? 因为键 '5' 只有一个值,所以没有什么可以减少的。

由于这些原因,最好先调用map。要获得所需的输出,您可以执行以下操作:

>>> print(element.map(lambda x: (x[0], x[1][1])).reduceByKey(lambda u, v: u+v).collect())
[('A', 50), ('5', 10)]

更新 1

还有一种方法:

您可以在reduce 函数中创建元组,然后调用map 来提取您想要的值。 (本质上颠倒了 mapreduce 的顺序。)

print(
element.reduceByKey(lambda u, v: (0,u[1]+v[1]))
.map(lambda x: (x[0], x[1][1]))
.collect()
)
[('A', 50), ('5', 10)]

注意事项

  • 如果每个键至少有 2 条记录,则使用 add_tuple_values() 会给您正确的输出。

关于python - 使用 reducebykey 错误 : int object is unsubscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com