我在我的 reducer 输出中得到一个列表列表而不是一个配对值,我不确定我的代码中要更改什么

I'm getting a list of lists in my reducer output rather than a paired value and I am unsure of what to change in my code

下面的代码几乎可以提供我想要但不完全是我想要的输出。

def reducer(self, year, words):
        x = Counter(words)
        most_common = x.most_common(3) 
        sorted(x, key=x.get, reverse=True)    
        yield (year, most_common)

这是给我输出

"2020" [["coronavirus",4],["economy",2],["china",2]]

我希望它能给我的是

"2020" "coronavirus china economy"

如果有人能向我解释为什么我得到的是列表列表而不是我需要的输出,我将不胜感激。以及关于如何改进代码以获得我需要的东西的想法。

来自 Counter.most_common 的文档解释了为什么您会得到一个列表列表。

most_common(n=None) method of collections.Counter instance
    List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.
    
    >>> Counter('abracadabra').most_common(3)
    [('a', 5), ('b', 2), ('r', 2)]

因为从最高频率到最低频率排序就像降序排序,但按字母顺序排序是升序,您可以使用自定义元组,在其中取频率的负数并按升序对所有内容进行排序。

from collections import Counter

words = Counter(['coronavirus'] * 4 + ['economy'] * 2 + ['china'] * 2 + ['whatever'])
x = Counter(words)
most_common = x.most_common(3)
# After sorting you need to discard the freqency from each (word, freq) tuple
result = ' '.join(word for word, _ in sorted(most_common, key=lambda x: (-x[1], x[0])))