首页 > 解决方案 > 对配对元组进行排序并获取前 n 个结果

问题描述

所以我有一个提供以下元组的函数。

keywords:  [('notre dame coach brian kelly', 21.0), ('put student-athlete health', 14.5), ('fourth acc game impacted', 12.5), ('student-athlete health', 10.5), ('football-related activities', 9.0), ('resuming team activities', 9.0), ('ongoing testing procedures', 8.0), ('october 3rd weekend', 8.0), ('players tested positive', 7.75), ('irish announced 13 players', 7.25), ('notre dame', 6.0), ('positive results', 4.5), ('players handled', 4.25), ('testing results', 4.0), ('primary focus', 4.0), ('prevention protocols', 4.0), ('positivity rates', 4.0), ('knew covid', 4.0), ('present challenges', 4.0), ('discussing options', 4.0), ('future opponents', 4.0), ('pause practices', 4.0), ('decision making', 3.5), ('playing field', 3.5), ('open date', 3.5), ('schools share', 3.5), ('coronavirus issues', 3.5), ('statement tuesday', 3.25), ('acc', 2.5), ('13 players', 2.25), ('game', 2.0), ('weekend', 2.0), ('irish', 2.0), ('testing', 2.0), ('coronavirus', 1.5), ('schools', 1.5), ('date', 1.5), ('decision', 1.5), ('playing', 1.5), ('statement', 1.25), ('saturday', 1.0), ('postponed', 1.0), ('isolation', 1.0), ('94 tests', 1.0), ('monday', 1.0), ('combined', 1.0), ('week', 1.0), ('quarantine', 1.0), ('result', 1.0), ('paused', 1.0), ('working', 1.0), ('reschedule', 1.0), ('safety', 1.0), ('continue', 1.0), ('follow', 1.0), ('managed', 1.0), ('increase', 1.0), ('august', 1.0), ('wonderfully', 1.0), ('season', 1.0), ('ll', 1.0), ('forefront', 1.0), ('forward', 1.0), ('back', 1.0), ('rescheduling', 1.0), ('oct', 1.0), ('involved', 1.0), ('saddened', 1.0), ('unable', 1.0), ('play', 1.0), ('based', 1.0), ('circumstances', 1.0), ('currie', 1.0), ('including', 1.0), ('possibility', 1.0), ('home', 1.0), ('opened', 1.0), ('win', 1.0), ('duke', 1.0), ('time', 1.0), ('days', 1.0), ('month', 1.0), ('rounds', 1.0), ('10', 0), ('3', 0)]

我正在尝试纠正一个计算前 n 个值的函数。由于它是一个元组,我认为我可以:

sorted(keywords, reverse = True) 

其中关键字是存储元组的绑定,但这不起作用。我尝试使用 Counter 但它似乎不适用于列表或元组。

def top_keywords(rake_keywords, n=3):
    """Given a RAKE keywords list of tuples in the form of:

        (keyword, score)

    return the top n keywords.

    rake_keywords is assumed to be in descending order by score, since that is
    how we get it from RAKE. Thus, simply return the first n terms extracted
    from their tuples.

    Returns: a list of strings. Returns an empty string if rake_keywords is empty.
    """
    counts = Counter(rake_keywords)
    most_common = counts.most_common(n)
    return most_common

我还是python的新手,经验不到两个月,所以提前谢谢你。

标签: pythonsorting

解决方案


sorted(keywords, reverse=True, key=lambda t: t[1])

您需要指定一个键来排序,它是元组的第二个元素


推荐阅读