本文主要介绍Python中,查找列表(list)中最大或最小的唯一对象元素的方法及示例代码。

示例数据:

[
{'Name':'c', 'result': 0},
{'Name':'java', 'result': 1},
{'Name':'python', 'result': 2},
{'Name':'python', 'result': 0},
{'Name':'python', 'result': 1},
]

示例结果:

[
{'Name':'c', 'result': 0},
{'Name':'java', 'result': 1},
{'Name':'python', 'result': 0},
]

1、通过sorted()实现

data = [
{'Name':'c', 'result': 0},
{'Name':'java', 'result': 1},
{'Name':'python', 'result': 2},
{'Name':'python', 'result': 0},
{'Name':'python', 'result': 1},
]

def find(data):
    #最小值
    step1 = sorted(data, key=lambda k: k['result'])
    #最大值 
    #step1 = sorted(data, key=lambda k: k['result'], reverse = True )
    print('step1', step1)
    step2 = {}
    for each in step1:
        if each['Name'] not in step2:
            step2[each['Name']] = each
    print('step2', step2)
    step3 = list(step2.values())
    print('step3', step3)
    print('\n')
    return step3

print(find(data))

2、通过itertools中groupby实现

from itertools import groupby

data = [
{'Name':'c', 'result': 0},
{'Name':'java', 'result': 1},
{'Name':'python', 'result': 2},
{'Name':'python', 'result': 0},
{'Name':'python', 'result': 1},
]

data = sorted(data, key=lambda x: x['Name'])
#最小值
res_min = [
    {'Name': g, 'result': min(v, key=lambda x: x['result'])['result']} 
    for g, v in groupby(data, lambda x: x['Name'])
]
#最大值
res_max = [
    {'Name': g, 'result': max(v, key=lambda x: x['result'])['result']} 
    for g, v in groupby(data, lambda x: x['Name'])
]

print(res_min)
print(res_max)

推荐文档