我有类似元组的列表
bottles = [(1234, 'ICED', 'MOC12', 3), (1234, 'ICED', 'MOC12', 2), (3456, 'HOT', 'CAR23', 1), (3456, 'HOT', 'YUP23', 2)]
我希望每个组的元组都与最后一个字段的最大值相对应。这些组由前三个值定义。
输出:
result = [(1234, 'ICED', 'MOC12', 3),(3456, 'HOT', 'CAR23', 1),(3456, 'HOT','YUP23', 2)]
答案 0 :(得分:1)
bottles = [(1234, 'ICED', 'MOC12', 3), (1234, 'ICED', 'MOC12', 2), (3456, 'HOT', 'CAR23', 1), (3456, 'HOT', 'YUP23', 2)]
sorted(bottles, key= lambda x: x[:3])
>>> [(1234, 'ICED', 'MOC12', 3),
(1234, 'ICED', 'MOC12', 2),
(3456, 'HOT', 'CAR23', 1),
(3456, 'HOT', 'YUP23', 2)]
您还可以使用max
而不是sorted
直接获得最大值。
答案 1 :(得分:1)
根据您的评论,这应该可行:
from itertools import groupby
bottles = [(1234, 'ICED', 'MOC12', 3), (1234, 'ICED', 'MOC12', 2), (3456, 'HOT', 'CAR23', 1), (3456, 'HOT', 'YUP23', 2)]
print([max(group) for key, group in groupby(sorted(bottles), lambda a: a[:3])])