Remove Duplicates From List Of Tuples Based On Highest Value
I've got list similar to that but its length will vary and the content too. I need to remove the duplicates of the 1st position in tuple, but I need to keep the highest value from
Solution 1:
>>> L=[('2186.11', '49'), ('1251.67', '48'), ('1267.67', '26'), ('1383.77', '824'), ('163.96', '29'), ('170.00', '29'), ('170.72', '51'), ('2186.11', '80'), ('170.00', '22')]
>>> list(dict(sorted(L, key=lambda v: int(v[1]))).items())
[('2186.11', '80'), ('170.00', '29'), ('1267.67', '26'), ('1383.77', '824'), ('163.96', '29'), ('1251.67', '48'), ('170.72', '51')]
Sort by the numerical value of the second item then convert to a dictionary to remove duplicates and convert back.
Solution 2:
assuming I understand what you're looking for:
example = [('2186.11', '49'), ('1251.67', '48'), ('1267.67', '26'), ('1383.77', '824'), ('163.96', '29'), ('170.00', '29'), ('170.72', '51'), ('2186.11', '80'), ('170.00', '22')]
example.sort(key=lambda x: int(x[1]))
result = list(dict(example).items())
result
[('1267.67', '26'),
('163.96', '29'),
('1383.77', '824'),
('1251.67', '48'),
('170.00', '29'),
('170.72', '51'),
('2186.11', '80')]
Post a Comment for "Remove Duplicates From List Of Tuples Based On Highest Value"