ssh26 ssh26 - 25 days ago 9
Python Question

How to find max values?

I need to find max of values for example:

[(12, 0.95), (15, 0.92), (20, 0.90), (12, 0.88), (15, 0.98), (12, 0.89)]


Output will max value corresponds with the id:

[(12, 0.95), (15, 0.98), (20, 0.90)]


How can I achieve this in python?

Any suggestions! Thanks for the help

Answer

Using just the basics:

data = [(12, 0.95), (15, 0.92), (20, 0.90), (12, 0.88), (15, 0.98), (12, 0.89)]

result_dict = {}
for id_num, value in data:
    result_dict[id_num] = max(value, result_dict.get(id_num, value))

result = sorted(result_dict.items())

print(result)

If the part inside the loop is confusing, here are other ways to write it:

if id_num in result_dict:
    result_dict[id_num] = max(result_dict[id_num], value)
else:
    result_dict[id_num] = value

or

if id_num in result_dict:
    if value > result_dict[id_num]:
        result_dict[id_num] = value
else:
    result_dict[id_num] = value

or

if id_num not in result_dict or value > result_dict[id_num]:
    result_dict[id_num] = value

or

if id_num > result_dict.get(id_num, value):
    result_dict[id_num] = value