慕婉清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)