I want to take average for all players with same name. I wrote following code. it's showing index error what's the issue?
Input: l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 122),('Ashwin', 90)]
Output: l = [('Kohli', 40), ('Ashwin', 61.5), ('Pujara', 122)]
t=0
l2=[]
for i in range(len(l)):for j in range(len(l)):if j < len(l) - 1 :if l[i][0] == l[j][0]:l2[t][0] = l[j][0]l2[t][1] = (l[j][1] + l[j+1][1]) / 2t = t + 1
One way with the help of default dict
from collections import defaultdict
data_dict = defaultdict(list)
l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 122), ('Ashwin', 90)]for k, v in l:data_dict[k].append(v)
data_dict = dict(data_dict)
# {'Pujara': [122], 'Ashwin': [33, 90], 'Kohli': [73, 7]}for k,v in data_dict.items():data_dict[k] = sum(v)/len(v)# {'Ashwin': 61.5, 'Kohli': 40.0, 'Pujara': 122.0}
To convert the dict to list of tuples you can use zip i.e
list(zip(data_dict.keys(),data_dict.values()))#[('Ashwin', 61.5), ('Pujara', 122.0), ('Kohli', 40.0)]
To find the maximum value you can use max i.e
max(data_dict.values()) #122
To get the key you can use
[i for i,j in data_dict.items() if j == max(data_dict.values())] # ['Pujara']