Python 中查找所有数据列表和相关标题的最高值和最低值的最有效算法是什么

在我的程序中有多个测验。用户进行测验,然后测验的标题和分数将保存到数据库中。为了便于示例,我将使用 Python 列表来表示它们:


[['quizTitle1', score], ['quizTitle2',score] ['quizTitle1', score] ['quizTitle3', score]]

我正在尝试打印出用户最弱的测验标题。


因此,使用 Python 列表示例,您会看到用户已参加测验 1两次。在第二次测验中,他们可能比第一次得到了更好的分数。因此,我需要获得用户在每次测验中获得的最高分(他们的最佳分数)。然后我需要找出哪个测验的分数最低、最好。


我目前的计划是这样的(伪代码)


While found = false

  1st = the first score selected that we are comparing with each other score

  2nd = the score we are comparing to the first

  For loop that repeats in the range of the number of lists

    If (2nd < 1st) or (2nd has the same title and greater mark than 1st):

       2nd becomes 1st

       Loop repeats 

    Else:

       New 2nd is the next list

  Found = true   

但最好的方法是什么?


芜湖不芜
浏览 161回答 4
4回答

慕婉清6462132

映射缩减方法:from itertools import groupbyfrom operator import itemgetterscores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]name, score = itemgetter(0), itemgetter(1)grouped_scores = groupby(sorted(scores), key=name)              # group by keyhighest_scores = (max(g, key=score) for _,g in grouped_scores)  # reduce by keylowest_highest = min(highest_scores, key=score)                 # reduceprint(lowest_highest)输出:['q1', 40]解释和生成器表达式的返回值groupby不是列表,如果您尝试直接打印它们,您会看到一堆无用的<itertools._grouper object at 0x7ff18bbbb850>. 但是使用将每个不可打印对象转换为列表list(),计算出的中间值如下:scores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]grouped_scores = [  ['q1', [['q1', 10], ['q1', 20], ['q1', 40]]],  ['q2', [['q2', 10], ['q2', 30], ['q2', 45]]]]highest_scores = [['q1', 40], ['q2', 45]]lowest_highest = ['q1', 40]Python 的map和reduce在本例中,我们正在寻找最高分数中的最低分数,因此在比较两个元素时,我们希望保留两者中的最小值。但在 python 中,我们可以直接调用整个序列,而不是min()重复应用该函数。reducemin()仅供参考,如果我们使用的话,代码将如下所示reduce:from itertools import groupbyfrom functools import reducescores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]name, score = itemgetter(0), itemgetter(1)grouped_scores = groupby(sorted(scores), key=name)  # group by keyhighest_scores = map(lambda x: max(x[1], key=score), grouped_scores)  # reduce by keylowest_highest = reduce(lambda x,y: min(x,y, key=score), highest_scores)  # reduceprint(lowest_highest)输出:['q1', 40]使用模块 more_itertools模块 more_itertools 有一个名为map_reduce的函数,它按键分组,然后按键减少。这照顾了我们的groupby和max步骤;我们只需要减少min就可以得到我们的结果。from more_itertools import map_reducefrom operator import itemgetterscores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]name, score = itemgetter(0), itemgetter(1)highest_scores = map_reduce(scores, keyfunc=name, valuefunc=score, reducefunc=max)lowest_highest = min(highest_scores.items(), key=score)print(lowest_highest)# ('q1', 40)

梵蒂冈之花

好吧,如果您愿意pandas,那么:import pandas as pdl = [["quizTitle1", 15],     ["quizTitle2", 25],     ["quizTitle1", 11],     ["quizTitle3", 84],     ["quizTitle2", 24]]df = pd.DataFrame(l, columns=["quiz", "score"])print(df)#          quiz  score# 0  quizTitle1     15# 1  quizTitle2     25# 2  quizTitle1     11# 3  quizTitle3     84# 4  quizTitle2     24lowest_score = df.iloc[df.groupby(['quiz']).max().reset_index()["score"].idxmin()]print(lowest_score)# quiz     quizTitle1# score            15# Name: 0, dtype: object

白板的微信

一个简单的:scores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]d = dict(sorted(scores))print(min(d, key=d.get))&nbsp; &nbsp;# prints q1该dict函数采用键/值对,我们只需要首先对它们进行排序,以便每个键的最后一个值是它最大的(因为最后一个是最终出现在字典中的值)。之后,所需的结果就是具有最小值的键。

鸿蒙传说

您可以使用字典来存储每个测验的值,并用列表中迄今为止看到的最大值更新其值,然后获取字典中所有值的最小值。scores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]d = {}for s in scores:&nbsp; d[s[0]] = s[1] if s[0] not in d else max(d[s[0]], s[1])print(d)print("Lowest best : ", min(d.values()))这打印:{'q1': 40, 'q2': 45}Lowest best :&nbsp; 40
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python