How to work out average of scores from a text file Python -


i want find out how sort out averages of scores text file, text file this:

matt 3 john 6 gucci 7 

notice there 1 space inbetween name , score.

from text file work out average of entire files content (scores).

my current code following:

    print("write 'avg' work out average of scores")     option = input ("\nenter option:  ")     list = []     option_class = input("\nwhich class wish preview: ")      1 = "1.txt"     2 = "2.txt"  if option =='avg'.lower():         if option_class == "1":                 name = input("\nwhat name? -  ")                  found = false                 open(one, 'r') f:                         data = f.readlines()                         line in data:                                 if name in line:                                         print("\n",line)                                         list.append(int(line.split()[2]))                                         found = true                         if found == false:                                 print("\nfalse")                  b = sum(list)                 len(list)                 avg = float(sum(list))/len(list) 

this contents in class 1, arguments sake we'll contents of text file 1 following:

matt 3 john 6 gucci 7 

is there easier method in shortening code more efficient or how make code read text file there 1 space between name , score. rather 'name - score'

you dont have f.readlines() , 'avg'.lower() not intending do, .lower() must used on option variable. avoid shadowing builtin functions , keywords did list.

sample code:

print(...) option = input(...) option_class = input(...)  if option.lower() == 'avg' , option_class == '1':  # .lower() on option.     name = input(...)     open(one) f:  # '-r' default omitting cleaner         # 1. iterate file handler directly without .readlines().         # 2. use list comprehension         # 3. avoid shadowing "list" using, say, "the_list"         the_list = [int(l.strip().split()[-1]) l in f if l.strip() , name in l.split()]          b = sum(the_list)         length = len(the_list)         # 1. dont repeat sum() & len() calls         # 2. default 0 avg avoid division 0.         avg = float(b) / length if length else 0 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -