为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

芜湖不芜 2023-06-27 14:15:15
在我的程序中有多个测验。用户进行测验,然后测验的标题和分数将保存到数据库中。为了便于示例,我将使用 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   但最好的方法是什么?
查看完整描述

4 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

映射缩减方法:

from itertools import groupby

from operator import itemgetter


scores = [['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 key

highest_scores = (max(g, key=score) for _,g in grouped_scores)  # reduce by key

lowest_highest = min(highest_scores, key=score)                 # reduce


print(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 的mapreduce

在本例中,我们正在寻找最高分数中的最低分数,因此在比较两个元素时,我们希望保留两者中的最小值。但在 python 中,我们可以直接调用整个序列,而不是min()重复应用该函数。reducemin()

仅供参考,如果我们使用的话,代码将如下所示reduce

from itertools import groupby

from functools import reduce


scores = [['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 key

highest_scores = map(lambda x: max(x[1], key=score), grouped_scores)  # reduce by key

lowest_highest = reduce(lambda x,y: min(x,y, key=score), highest_scores)  # reduce

print(lowest_highest)

输出:


['q1', 40]

使用模块 more_itertools

模块 more_itertools 有一个名为map_reduce的函数,它按键分组,然后按键减少。这照顾了我们的groupbymax步骤;我们只需要减少min就可以得到我们的结果。

from more_itertools import map_reduce

from operator import itemgetter


scores = [['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)


查看完整回答
反对 回复 2023-06-27
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

好吧,如果您愿意pandas,那么:

import pandas as pd


l = [["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     24

lowest_score = df.iloc[df.groupby(['quiz']).max().reset_index()["score"].idxmin()]

print(lowest_score)

# quiz     quizTitle1

# score            15

# Name: 0, dtype: object


查看完整回答
反对 回复 2023-06-27
?
白板的微信

TA贡献1883条经验 获得超3个赞

一个简单的:


scores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]


d = dict(sorted(scores))

print(min(d, key=d.get))   # prints q1

该dict函数采用键/值对,我们只需要首先对它们进行排序,以便每个键的最后一个值是它最大的(因为最后一个是最终出现在字典中的值)。之后,所需的结果就是具有最小值的键。


查看完整回答
反对 回复 2023-06-27
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

您可以使用字典来存储每个测验的值,并用列表中迄今为止看到的最大值更新其值,然后获取字典中所有值的最小值。


scores = [['q1', 20],['q2',30],['q1',40],['q2',10],['q2',45],['q1',10]]

d = {}

for s in scores:

  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 :  40


查看完整回答
反对 回复 2023-06-27
  • 4 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信