从具有公共元素的子列表中查找最大值

Find the maximum value from sublists with common element

我有一个嵌套列表:

input_list = [[12, 123182, 94], [12, 125201, 6], [13, 123180, 3], [13, 125272, 93], [13, 125987, 4]]

我需要根据列表中公共的第一个元素找到第三个元素具有最大值的子列表,并且 return 新列表中该子列表中的前两个元素。

期望的输出:

output_list = [[12, 123182], [13, 125272]] 

在上面的示例中,公共元素是 12 和 13,这些子列表中第三个元素的最大值分别是 94 和 93。

给你。所有解释都在评论中。我认为这是非常简单的代码——唯一的例外是 max() 函数的 'key' 参数,它不是很流行。

input_list = [[12, 123182, 94], [12, 125201, 6], [13, 123180, 3], [13, 125272, 93], [13, 125987, 4]]
# desired_output_list = [[12, 123182], [13, 125272]]

# get the all possible 1st values
keys = {i[0] for i in input_list}

# group data into dict of lists, with 1st value as a key
input_as_dict = dict()
for k in keys:
    input_as_dict[k] = [i for i in input_list if i[0] == k]

print(f'input_as_dict = {input_as_dict}')

output_list = []
for k, v in input_as_dict.items():
    # calculate max within each key
    m = max(v, key=lambda x: x[2])  # use 'key' argument to calculate maximum within list of lists based on 3rd element of a list
    print(f'max for key={k} is: {m}')
    output_list.append(m[:2])  # adding truncated (3rd element removed) list to final output

print(output_list)