Hi, this is my first post. I apologize if I make any mistakes.
I have a problem where I need to take a list and print it out as a table of average
for each person. The list is : [('tom',4),('ben',5),('tom',8),('ben',12)]

So far my code is:

def getAverage(list):
    list = [('tom',4),('ben',5),('tom',8),('ben',12)]
    for item in list:
....
....

I know the formula to take average and sum but i'm not sure how to do it here
since there are two same names of each.
I have to print a table of average score for both persons. Not sure how to start.
Any help would be great!

Recommended Answers

Try with name, points instead of item at line 3. list is built in type so change it to something better describing the purpose. Line 2 does not belong in function as it overwrites the parameter.

Jump to Post

All 3 Replies

Try with name, points instead of item at line 3. list is built in type so change it to something better describing the purpose. Line 2 does not belong in function as it overwrites the parameter.

I like dictionaries, I made a function see if you can tell what it does from this:

>>> grade_buk=[('tom',4),('ben',5),('tom',8),('ben',12)]
>>> grades=average(grade_buk)

>>> for key in grades:
	print(key.title()+':',grades[key])

	
Ben: 8.5
Tom: 6.0

I like (built in) functions and generators:

>>> def nth_for(name, seq, n=1):
	return [item[n] for item in seq if item[0]==name]
>>> def names(seq):
	return set(name for name, _ in seq)
>>> names(grade_buk)
set(['ben', 'tom'])
>>> average(nth_for('ben', grade_buk))
8.5
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.