Home > Blockchain >  calculating the mean of numeric values in a list of tuples
calculating the mean of numeric values in a list of tuples

Time:11-07

I'm new to Python and stumbled upon the following issue: I have two lists (listA and listB) consisting of tuples ('str', float) and I have to calculate the mean of the float values for each list.

groups = ['A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A']
scores = [0.2, 0.3, 0.9, 1.1, 2.2, 2.9, 0.0, 0.7, 1.3, 0.3]

list_groups_scores = list(zip(groups,scores))
list_groups_scores.sort()
    
print(list_groups_scores)


listA = list_groups_scores[0:4]
listB = list_groups_scores[5:9]
print(listA, listB)

Can anyone help? Thanks a lot!

CodePudding user response:

Use a dict to hold the group and the scores

from collections import defaultdict

groups = ['A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A','K']
scores = [0.2, 0.3, 0.9, 1.1, 2.2, 2.9, 0.0, 0.7, 1.3, 0.3,1]
data = defaultdict(list)
for g,s in zip(groups,scores):
  data[g].append(s)
for grp,scores in data.items():
  print(f'{grp} --> {sum(scores)/len(scores)}')

output

A --> 0.725
B --> 1.1666666666666667
K --> 1.0

CodePudding user response:

Try the following code:

sum = 0
ii=0
for sub in listA:
    ii =1
    i=sub[1]
    sum = sum   i
avg=sum/ii

CodePudding user response:

s = lambda x:[i[1] for i in x]

print(sum(s(listA))/len(listA))

print(sum(s(listB))/len(listB))

CodePudding user response:

There is a special type of loop in python that looks like this.

listANumbers = [i[1] for i in listA]

It loops through every element in listA and sets every element[1] to a new list.

result:

[0.2, 0.3, 1.1, 1.3]

You can then take the sum and average of the new list.

listANumbers = [i[1] for i in listA]
meanA = sum(listANumbers) / len(listANumbers)

CodePudding user response:

Sum on unpacked values in list and divide by list length

sum(v for l,v in listA) / len(listA)

CodePudding user response:

meanA = sum(list(zip(*listA))[1]) / len(listA)
meanB = sum(list(zip(*listB))[1]) / len(listB)
print(meanA, meanB, sep='\n')

Prints:

0.7250000000000001
1.025
  • Related