I have a list of tuples. Each tuple contains 2 elements:
For example, the list may be
pathList = [
((1, 2), 4),
((1, 4, 2), 2),
((1, 2), 6),
((1, 2), 3),
((1, 4, 2), 3)
]
Now I want to remove tuples which have the same paths (1st element) as others, while keeping the one that has the highest score (2nd element) among them.
For example, after the process, pathList
should be
pathList = [
((1, 2), 6),
((1, 4, 2), 3)
]
The order is not important.
Is there an efficient way to do it?
You can use a dictionary (dict.setdefault method)to preserve your paths as key and relative scores as a set (O(1) complexity for adding values) of values then select the max score for each unique path :
>>> pathList = [
... ((1, 2), 4),
... ((1, 4, 2), 2),
... ((1, 2), 6),
... ((1, 2), 3),
... ((1, 4, 2), 3)
... ]
>>>
>>> d={}
>>> for i,j in pathList:
... d.setdefault(i,set()).add(j)
...
>>> [(i,max(j)) for i,j in d.items()]
[((1, 2), 6), ((1, 4, 2), 3)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With