I'm just curious to know if there is a better way to find all the maximum numbers in a list.
As an example, i have a list of dictionaries. which has a key ("info") with corresponding value of dictionary as shown below. I want to find the maximum numbers ("count") from that list. once the maximum numbers are found, the corresponding "code" for that element has to be determined.
I am able to do it as below, but for a really large list, the execution time will be high.
codes = [{"code": 1, "info": {"status": "running", "count": 4}},
{"code": 2, "info": {"status": "running", "count": 1}},
{"code": 3, "info": {"status": "running", "count": 2}},
{"code": 4, "info": {"status": "running", "count": 4}},
{"code": 5, "info": {"status": "running", "count": 4}}
]
count_max = 0
filtered_codes = []
for i in range(len(codes)):
if codes[i]['info']['count'] == count_max:
filtered_codes.append(codes[i]['code'])
if codes[i]['info']['count'] > count_max:
filtered_codes.clear()
filtered_codes.append(codes[i]['code'])
count_max = codes[i]['info']['count']
print(filtered_codes)
output : [1, 4, 5] #1,4,5 are the code for dictionary with count == 4 (max amongst all the count)
so, is there any better way to do this? may be using like filter, lambda, max ?
Edit : Someone had posted the below code as answer, later got deleted
max_count = max(info["info"]["count"] for info in codes)
filtered_codes = [val["code"] for val in filter(lambda x: x["info"]["count"] == max_count, codes)]
So i ran both the code on a list of length 1000000
The first approach posted by me took : 1.4539954662322998s
Second approach took : 0.4440000057220459s
So is the second approach best solution?