2

I have scores in a txt file and have imported the name, score into a blank list. I need to know how to get an average score from the list for the txt file.

code

 column = []     
 for line in open('name,score.txt','r').readlines():
          column.append(line.strip(':'))

The text file data

 pon : 9
 jon : 3
 bob: 10
 zack : 4
 cam : 5
 tim : 3

How do I get an average from the list???

6 Answers 6

2

There are a few fixes required

column = []
for line in open('test.txt','r').readlines():
       column.append(line.strip().split(':')[1])  # Strip the new lines
                                                  # Split on the :
                                                  # Append the second value
column = map(int,column)                          # Convert everything to int
avg = sum(column)/len(column)                     # Find the average using sum
print (avg)                                       # Finally print it

Note that Kasra's answer is more pythonic way to do it. I have just corrected your code.

Sign up to request clarification or add additional context in comments.

2 Comments

avg = sum(column)/len(column) ValueError: invalid literal for int() with base 10: 'pon : 9\n'
I guess you changed line.strip().split(':')[1] in your code, Or the sample text file attached is not exactly matching with file on your machine. @user00
1

As per the format of your text file is concerned, after splitting each line on : you will get a list with two values, first then name and second the marks, So you need to use line.split(':')[1], The after iteration of the file is finished, you have some strings in the column list, to perform any arithmetic operations on the contents of the list you need to convert all those elements of the list to int which is done by using map() function.

Also If you are using Python 2.x then you explicitly need to convert either one of sum(list) or len(list) to float, Otherwise the average would always be returned as an int.

column = []
for line in open('name,score.txt','r').readlines():
    column.append(line.strip().split(':')[1])
column_int = map(int, column)
print "average = ", sum(column_int)/float(len(column_int))

1 Comment

You forgot to strip the newlines here
0

You are over-complicating it guys. Just extract numbers from the file using isdigit()

    list_ = [float(x) for x in open(FILE).read().split() if x.isdigit()]
    m = 1. *sum(list_) / len(list_)

Comments

0

Get all the numbers (don't forget to convert them to integers) and do this

x=sum(list_of_numbers)

Here x contains the sum. Then divide the sum by the length of this list.

for line in open('name,score.txt','r').readlines():
    column.append(int(line.split(':')[1]))
print sum(column) / len(column)

2 Comments

get an error message: NameError: name 'list_of_numbers' is not defined
@user00, <sarcasm>really?!</sarcasm> That was just an example. The actual code is at the end (it starts with for line...
0

You don't need to use readlines also as a more pythonic way for dealing with files you can use with statement and then use a generator expression within sum function :

 with open('name,score.txt','r') as f :
      s=sum(int(line.split(':')[-1]) for line in f)
      l=sum(1 for _ in f)
      avg=s/l

1 Comment

l is 0 hence ZeroDivisionError the file is at the end after the first full iteration.
0

Use float to convert the strings to avoid integer divisison in Python 2:

with open('name,score.txt','r') as f :
    data = [float(line.split(':')[-1]) for line in f]
    avg = sum(data) / len(data)

The with context manager guarantees that the file will be closed. The list comprehension [float(line.split(':')[-1]) for line in f] reads the last column after the : into a list of floats. Finally, the average is the sum of all numbers divided by the count, i.e. the length of the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.