Finding averages from strings in a list in Python 3

I have a list of scores like so:

scores = ["Bob Foo - 10 / 20\n",
      "Jim Foo - 5 / 20\n",
      "Bob Foo - 7 / 20\n",
      "Jack T - 6 / 20\n",
      "Jack T - 4 / 20\n",
      "Bob Foo - 9 / 20\n"]

I need to try and find the average score of each person seperately rounded to the nearest integer. The list may vary its scale and names will change but it will always have the format of: first name last name - score / 20.

I want an output of something like:

>>> Bob Foo - 9
Jim Foo - 5
Jack T - 5

I really don't know what to do here. I know about the sorted function and how you can specify a key but I don't know if that will help here.

The closest I've gotten is:

for score in scores:
    print(re.split(r'[-/]',score))

which isn't even close, because all it does is split up the list and give me this:

>>> 
['Bob Foo ', ' 10 ', ' 20\n']
['Jim Foo ', ' 5 ', ' 20\n']
['Bob Foo ', ' 7 ', ' 20\n']
['Jack T ', ' 6 ', ' 20\n']
['Jack T ', ' 4 ', ' 20\n']
['Bob Foo ', ' 9 ', ' 20\n']
>>> 

How can I overcome this? Can I just create a function that finds the average score of each person in a list?

Edit:

I could simplify the list of scores to an easier format. For example:

scores = ["Bob Foo 10\n",
      "Jim Foo 5\n",
      "Bob Foo 7\n",
      "Jack T 6\n",
      "Jack T 4\n",
      "Bob Foo 9\n"]

Answers


I find it useful to divide-and-conquer programming tasks. Divide the complex task into a series of trivially simple tasks. Either you know how to do each one individually, or you can receive more targeted help on the part you are struggling with.

As an example, here is how I would solve this problem:

import re
scores = ["Bob Foo - 10 / 10\n",
          "John Smith - 5 / 10\n",
          "Bob Foo - 7 / 10\n",
          "Jack T - 6 / 10\n",
          "Jack T - 4 / 10\n",
          "Bob Foo - 9 / 10\n"]

# First, split the names and scores up
scores = [re.match('(\S+ \S+) - (\d+)', score).groups() for score in scores]
#print (scores)

# Convert the number string into an integer
scores = [[score[0], int(score[1])] for score in scores]
#print (scores)

# Create a dictionary, keyed by the name
names = set(score[0] for score in scores)
scores = {
    name: [score[1] for score in scores if name == score[0]]
    for name in names
}
# print (scores)

# Compute the average for each name
scores = {
    name: sum(score)/len(score)
    for name, score in scores.items()
}
print (scores)

Need Your Help

Better way to read last portion of URL

php string url search url-parsing

This script should detect the last portion in the full path, and if it is stackoverflow output ok

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.