Home > Mobile >  Reading a line in a text file, seperating numbers from words and getting the average of the the numb
Reading a line in a text file, seperating numbers from words and getting the average of the the numb

Time:11-30

I have two lines in a text file- ,,Frank 10 4 6 8 9,, and ,,Oliver 8 6 9 2 10,,. I have to seperataly print the names. Then i have to sum the numbers and print the average. My code is a tragedy, please help. So the output should be something like: Frank average Oliver average

File = open("Mokiniai.txt","r")
Digit = 1
Avrg= 0
for line in File:
    a = 0
    line = line.strip("\n")
    print(line.split(" ")[0])
    
    for substring in line:
        x = (line.split(" ")[Digit])
        Digit = Digit   1
        Avrg = Avrg   int(x)
    print(Avrg/Digit)

CodePudding user response:

Try this:

with open('Mokiniai.txt', 'r') as your_file:
    content = your_file.read()

for line in content.split('\n'):
    name, *numbers = line.split(' ')
    avg = sum(map(lambda n: float(n), numbers)) / len(numbers)
    print(name, avg)

CodePudding user response:

Try running the below code:

file = open("Mokiniai.txt","r")
lines = file.read().split('\n')
for line in lines:
    split_list = line.split(' ')
    name = split_list[0]
    numbers = [int(x) for x in split_list[1:]]
    print (name   " "   str(sum(numbers)/len(numbers)))

It shall give the following output:

Frank 7.4
Oliver 7.0
  • Related