Reputation: 99
How to fix the number of occurrence in a list of tuples and return an item with max value.
given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
expected = [('c',5),('a',3),('b',3)]
How do you do this without doing anything to complex.
Upvotes: 0
Views: 65
Reputation: 26315
A very straightforward approach is to group the tuples in a dictionary, then just get the maximum (letter, number)
value from each letter
key in the dictionary:
from collections import defaultdict
from operator import itemgetter
given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
d = defaultdict(list)
for key, value in given:
d[key].append((key, value))
>>> print(dict(d))
{'b': [('b', 3)], 'a': [('a', 2), ('a', 3)], 'c': [('c', 5), ('c', 5)]}
>>> print([max(x[1], key = itemgetter(1)) for x in sorted(d.items())])
[('a', 3), ('b', 3), ('c', 5)]
Without using external libraries:
given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
d = {}
for key, value in given:
if key not in d:
d[key] = []
d[key].append((key, value))
>>> print(d)
{'b': [('b', 3)], 'a': [('a', 2), ('a', 3)], 'c': [('c', 5), ('c', 5)]}
>>> print([max(x[1], key = lambda x: x[1]) for x in sorted(d.items())])
[('a', 3), ('b', 3), ('c', 5)]
Upvotes: 1
Reputation: 99
given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
expected = dict(given).items()
dict_items([('a', 3), ('b', 3), ('c', 5)])
Upvotes: -1
Reputation: 4199
from itertools import groupby
groups = groupby(sorted(given, key = lambda x: x[0]), key = lambda x: x[0])
print [max(g) for k,g in groups]
results in
[('a', 3), ('b', 3), ('c', 5)]
Upvotes: 2
Reputation: 43186
Here is one way:
given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
expected = dict(sorted(given)).items()
sorted(...)
When you sort the list, all the items with a low value (second element) are moved to the front of the list.
dict(...)
When you convert the sorted list to a dict, the lower values are replaced by the higher values which are closer to the end of the list.
Upvotes: 1