我怎么能不能索引到reduce的值列表?

时间:2012-09-23 20:43:42

标签: mapreduce mrjob

我通过Python mrjob模块在Map Reduce作业中使用in-mapper组合。因为我写了一个mapper_final函数,它发出一对,我确信只有一个键值对被发送到我的reducer。

然而,我的reduce功能错误:

  def reducer(self, key, occurrences):
    '''
    Calculates the final value.
    '''
    yield 'Final Value: ', occurrences[0] / 2

错误读取

File "calculateFinalValue.py", line 354, in reducer
    yield 'Final Value: ', occurrences[0] / 2
TypeError: 'generator' object has no attribute '__getitem__'

为什么我不能索引到occurrences?该列表中应该只有一对,对吧?

1 个答案:

答案 0 :(得分:3)

occurrences不是list,而是generator。如果需要list,则需要将生成器结果组合到列表中。类似的东西:

list_occurrences = [ occ for occ in occurrences ]

list_occurrences = list(occurrences)

yield 'Final Value: ', list_occurrences[0] / 2

或者您可以使用occurrences.next()获取第一个出现值:

yield 'Final Value: ', occurrences.next() / 2