Python problem

John Parker parkjv1 at gmail.com
Mon Mar 28 20:38:05 EDT 2011


Dear all,

This is the solution that I came up with to deal with handling the file of
scores.

Thank you all for your feedback!

John


# define calc average function
def calcAve(mylist):
    total = 0
    count = 0
    for i in range (0, len(mylist)):
    # count scores for even number items in index
        if (i % 2 == 0):
            total = total + float(mylist[i])
            count = count + 1
    return total/count

#Open file called scores and read in data, store in list called lines
infile = open("scores.txt", "r")
lines = infile.readlines()
infile.close()
#print lines
# Create and empty list called names, scores and averages
names = []
averages=[]

#1st for loop to deal with Rows, i.e. names
for line in lines:
    tokens = line.split(",")
    names.append(tokens[0].strip())
    scores = []
    #2nd for loop (nested loop) to deal with columns, i.e. scores
    for i in range (1, len(tokens)):
        scores.append (tokens[i])
        #print scores
    # define average var, call calcAve function to be used on list called
scores    
    average = calcAve(scores)
    #print average
    #append avg scores to var called averages
    averages.append(average)
#    print averages

for i in range (0, len(names)):
    print names[i], "score: ", averages[i]




On 3/28/11 12:18 PM, "Rhodri James" <rhodri at wildebst.demon.co.uk> wrote:

> On Mon, 28 Mar 2011 22:38:29 +0100, John Parker <parkjv1 at gmail.com> wrote:
> 
>> infile = open("scores.txt", "r")
>> lines = infile.readlines()
>> infile.close()
>> tokens = lines.split(",")
>> names = []
>> scores = []
> 
> [snippety snip]
> 
>> error:
>> Traceback (most recent call last):
>>   File "Score_8.py", line 38, in <module>
>>     tokens = lines.split(",")
>> AttributeError: 'list' object has no attribute 'split'
>> 
>> So, what am I doing wrong?
> 
> Exactly what the traceback says: you're taking `lines`, the list you
> created of all the lines in the file, and trying to split the list *as a
> whole* on commas.  That doesn't work.  You split strings, not lists.  By
> the looks of it that line is something left over from a previous attempt.
> Just delete it, it's not doing anything useful for you.





More information about the Python-list mailing list