如果第一个和第二个元素相同,则查找列表列表的最大值

FInd the max value of a list of list if the first and second elements are the same

我有他的名单:

[['191', '279', '1488', '1425']
['191', '279', '1488', '855']
['191', '279', '1488', '1140']
['191', '279', '1488', '285']
['191', '279', '1488', '665']
['191', '279', '1488', '570']
['104', '264', '1488', '1140']
['191', '279', '1488', '760']
['104', '264', '1488', '760']
['104', '264', '1488', '665']
['104', '264', '1488', '1425']
['104', '264', '1488', '285']
['104', '264', '1488', '855']]   

如果第一个和第二个值相同,我需要使用循环找到最大值,否则我取唯一值。

例如,这里我想要结果:

maxlist = [['191','279','1488','1425'],['104','264','1425']]

我已经试过了:

maxlist = []
    for i in res:
        i = i.split(";")
        finallist.append(i)


    for i in finallist:
         for x in finallist:
             if x[0] == i[0] and x[1] == i[1]:
                 maxlist.append(int(x[3]))
                 try:
                     finallist.remove(i)
                 except:
                     pass

         maxresult = max(maxlist)
         valueA = x[0]
         valueB = x[1]
         valueC = x[2]

         print(valueA+str(" ")+str(valueB)+str(" ")+str(valueC)+str(" ")+str(maxresult))

你的问题有点不清楚,但如果你想要每个子列表的第四个值等于最大第四个值,你可以使用这个:

maxlist = list(filter(lambda x: int(x[3]) == max(x for x in map(lambda x: int(x[3]), inputlist)),inputlist))

如果重复答案与其他数据一起出现,您可以删除它们,或者删除第三个值等。

假设您想在最后一列中找到具有最大整数值的元素,并按前两列分组,您可以执行以下操作:

from itertools import groupby
from operator import itemgetter

sample_data = [
    ["191", "279", "1488", "1425"],
    ["191", "279", "1488", "855"],
    ["191", "279", "1488", "1140"],
    ["191", "279", "1488", "285"],
    ["191", "279", "1488", "665"],
    ["191", "279", "1488", "570"],
    ["104", "264", "1488", "1140"],
    ["191", "279", "1488", "760"],
    ["104", "264", "1488", "760"],
    ["104", "264", "1488", "665"],
    ["104", "264", "1488", "1425"],
    ["104", "264", "1488", "285"],
    ["104", "264", "1488", "855"],
]

# groupby needs data do be sorted by the same key.
sorted_data = sorted(sample_data, key=itemgetter(0, 1))

# group 4-tuples by the first two values. 
grouped = groupby(sorted_data, key=itemgetter(0, 1))


def get_last_element_value(element):
    # We need the integer value of the string to compare the elements,
    # so we cannot use itemgetter and instead use our own key function.
    return int(element[-1])


result = [max(elements, key=get_last_element_value) for _, elements in grouped]

您会在 stdlib 文档中找到对 groupby 的很好解释。