Python Script Calculating Average

Can anyone explain what each line of the code does and how it works? I have no experience with python so I am not sure how the arrays and such work. I found this code while looking through the forums.

f = open("exams","r")

l = f.readline()
while l:
    l = l.split(" ")
    values = l[1:]
    
    sum = 0.0
    for v in values:
        sum += float(v)
    
    print "%s %f" % (l[0] , sum / len(values))
    
    l = f.readline()
    
f.close()

Thank you for any help.

f = open("exams","r") # opens the file exams to read

l = f.readline() # reads the first line
while l: # loop while there's a line
    l = l.split(" ") # split the line into an array
    values = l[1:] # makes a copy of array l without the first element
    
    sum = 0.0 # assign a float 0.0 to sum
    for v in values: # loop through the array values
        sum += float(v) # adds to sum the floating point representation of the current (v) for value
    
    print "%s %f" % (l[0] , sum / len(values)) # display results of average
    
    l = f.readline() # load another line from exams
    
f.close() # close the file exams
1 Like

Thanks so much! What is len?

It is a function of python to return the length (the number of items) in an object.
In this case number of values.

Okay, I want to do something similar but with strings and dictionaries. If I have this file:

25 apple orange
2 carrot peach chicken
50 banana grape

I want to split this up into id and name where id is the number and name is the rest of the string. Then I want to store the entries into a dictionary. I was looking at the dictionary function and was wondering how it would work. I started it but don't know how to put it into a dictionary.

f = open("food","r")

l = f.readline()
while l:
	l = l.split(" ")
	id, name = l.split(" ")
        dict = {???}
1 Like

Can I just add dict.sort to sort it numerically by id? And once I sort it, how do I print it out? I didn't really understand the %formatting from the previous one.

> Can I just add dict.sort to sort it numerically by id?
Yes, you can sort the keys of a dictionary. Nevertheless, you should use

sorted(dict)

> And once I sort it, how do I print it out?
That depends of what version of python you are using

---------- Post updated 10-20-14 at 12:40 PM ---------- Previous update was 10-19-14 at 08:46 PM ----------

> I didn't really understand the %formatting from the previous one.
That was formatting for python 2.x

Let's avoid formatting for now.

# sort the dictionary keys and use key to print
for key in sorted(dict):
   # dict[key] is an array of fruits. join will make it a string. Remove the # infront of your version.
   # print(key, ": ", " ". join(dict[key])) # for python 3.x
   # print key, ": ", " ". join(dict[key])  # for python 2.x
1 Like

Oh, thank you! That makes everything much clearer.

I am playing around with python scripting again and was wondering, if I was to read a file with a list of baseball teams how would I list out all the teams in alphabetical order?

Maybe,

#!/usr/bin/python

# open the file for reading
f = open("file", "r")

# read the whole file into array, using each line as an element
lines = f.readlines()

# dismiss the file
f.close()

# sort each line alphabetically in place
# the original lines array is not modified
for l in sorted(lines):
    # This is for 2.x and the trailing , is necessary to prevent automatically
    # adding a new line. f.readlines included the new line already. 
    print l,

So the sorted function automatically sorts alphabetically, not numerically.
If the team name is the third element, how would I just pull out the team name and sort them?
Example: Howard,Ryan,Phillies,1b,529,142,26,0,47,136,.268

You need a more complex construct to do that, now we need to split the line into tokens.

#!/usr/bin/python

f = open("file3", "r")
lines = f.readlines()
f.close()

for l in sorted(lines, key=lambda x: x.split(',')[2]):
    print l,

Perhaps some more about it?

1 Like

Thank you! Thank you! I will read up more about it. I will keep playing with it and I'll be back if I have anymore questions.

---------- Post updated at 08:12 PM ---------- Previous update was at 08:32 AM ----------

One last question about this, is it possible to create something like a menu that allows someone to pick a team and then it will print out all the players?

It is possible. In fact, I think it would be a good exercise for learning.
I would suggest a dictionary where the key is the team and the value is an array of players.

I am trying to do that but I am having a little trouble. Here is how I started it:

team = {}
team['1']= ?
team['2']= ?
team['3']= ?
team['4']= ?
team['5']= ?
while True: 
  options=team.keys()
  options.sort()
    for entry in options: 
      print entry, team[entry]

    selection=raw_input("Please Select:") 
    if selection =='1': 
      print ???? 
    elif selection == '2': 
      print ????
    elif selection == '3':
      print ???? 
    elif selection == '4': 
      print ????
	elif selection == '5':
    else: 
      print "Unknown option selected, please try again." 

For the dictionary of teams do I put in the team names? Or since I am reading from a file do I set it in some way?

A few steps that might get you going.

Let's create an empty dictionary teams

teams = {}

Let's assume you read from a file

line = "Howard,Ryan,Phillies,1b,529,142,26,0,47,136,.268"

This is extracting lastname, firstname and team from line

lname, fname, team  = line.split(',')[:3]

If there's no value yet assigned to the team the array must be created first, here I am creating it empty, but it can be done assigning a first player, after that you can just append new players

teams[team] = []

Appending a new player to the team

teams[team].append(" ".join([fname, lname]))

Now to access that team you only have to issue

print(", ".join(teams["Phillies"]))

You might want to validate what the user input

if selection in teams:
	print(", ".join(teams[selection]))

Remove the first set of () around print if you are using python 2.x

If there are multiple lines in the file with different teams and players, then how would you set each line to a line to extract from?
To make things easier, let's say each line you read from is formatted in the same name with lname, fname, team, and statistics.

You could refer back to your post #1 and see how a file could be read line by line.

Here's a more Pythonic and succinct way

with open("file") as f:
    for line in f:
        lname, fname, team  = line.split(',')[:3]
        <continue placing it into a dict, etc...>

Okay, I am trying to put everything together, and I am a little lost.

#!/usr/bin/python

f = open("test", "r")
lines = f.readlines()
f.close()

for l in sorted(lines, key=lambda x: x.split(',')[2]):
    print l,


team = {}
with open("test") as f:
    for line in f:
        lname, fname, team  = line.split(',')[:3]
   while True:
  options=team.keys()
  options.sort()
    for entry in options:
      print entry, team[entry]

     selection=(raw_input("Please Select: "), 'r')
    if selection =='0':
      print(", ".join(teams[selection]))
    elif selection == '1':
      print(", ".join(teams[selection]))
    elif selection == '2':
      print(", ".join(teams[selection]))
    elif selection == '3':
      print(", ".join(teams[selection]))
#   elif selection == '4':)
    else:
      print "Unknown option selected, please try again."