Terr_code Terr_code - 1 year ago 51
Python Question

opening txt file and creating list and getting basic stats

I am trying to open a textfile called state_meet.txt file; the info is formatted as

see example:

Lanier City Gymnastics,Ben W.,55.301
Lanier City Gymnastics,Alex W.,54.801
Lanier City Gymnastics,Sky T.,51.2
Lanier City Gymnastics,William G.,47.3 etc..

and create functions to get info such as:

The total count of gymnasts that participated in the state meet.
The first place score.
The last place score.
The score differential between the first and last place.
The average score for all gymnasts.
The median score. (The median is the grade at the mid-point of a sorted list. If there is an even number of elements in the list, the median is the average of the 2 middle elements.)
The average of all scores above the median (not including the median).
The average of all scores below the median (not including the median).
The output should look as such

Summary of Data:
Number of gymnasts: 103
First place score: 143.94
Here's the code I have so far:

with open('state_meet.txt','r') as f:
for line in f:
allt = []
values = line.split()

max_val = max(values[3])


min_val = min(values[3])


total = sum(input_list)
length = len(input_list)
for nums in [input_list]:
mean_val = total / length

med_val = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2

this is what i have so far but my text is reading it as W.,55.301 instead of 55.301 and giving me errors

Answer Source
  1. You should use split(',') to replace split().
  2. Use values[2] to get the third item of list values.
  3. list allt seems no use.
  4. It seems that no matter how many lines are there in state_meet.txt, values always gets the last line data.

I guess the things you want to do:

import collections
names = ["gymnastics_school", "participant_name", "all_around_points_earned"]
Data = collections.namedtuple("Data", names)

data = []

with open('state_meet.txt','r') as f:   
    for line in f:
        line = line.strip()
        items = line.split(',')
        items[2] = float(items[2])

max_one = max(data, key=lambda d:d.all_around_points_earned)
print(max_one.all_around_points_earned) # max val

min_one = min(data, key=lambda d:d.all_around_points_earned)
print(min_one.all_around_points_earned) # min val

total = sum(d.all_around_points_earned for d in data)
mean_val = total/len(data)
print(mean_val) # mean val

sorted_data = sorted(data, key=lambda d:d.all_around_poiints_earned)
if len(data)%2==0:
    a = sorted_data[len(data)/2]
    b = sorted_data[len(data)/2-1]
    median_val = (a+b)/2
    median_val = sorted_data[(len(data)-1)/2]
print(median_val) # median val