How to sum all the elements (except for the first one) in rows in 2d list?

Question:

So, my task is to write a program which gets an integer on the input, then times asks for the student’s name (one word) and a space-separated list of their grades, and on the output there should be a list of tuples, where each tuple consists of the student’s name and their grade point average, rounded to integers.

Example:

Input:

3

Ann 5 6 7 8

Ben 10 10 0 0

Fred 7 6 8 5

Output:

[(‘Ann’, 6), (‘Ben’, 5), (‘Fred’, 6)]

Now my program looks like this:

n = int(input())
a = list()
for i in range(n):
  a.append(input().split())
print(tuple(a))

I have no idea how to sum numbers in each row (except for the first string, student’s name) and make it like a new list. Maybe I should somehow use numpy in this case, but still don’t know how. I will be grateful for any help

Asked By: Catherine

||

Answers:

Iterate over a and for each sublist, create a tuple out of the first item and the mean of the remaining items. You can use the built-in statistics.mean and then convert its result to an int:

from statistics import mean

n = int(input())
a = [input().split() for _ in range(n)]
result = [
    (name, int(mean(float(s) for s in scores)))
    for name, *scores in a
]
print(result)
Answered By: Samwise
  • After splitting each line on a space, the first element of the result is the name, and the rest of the elements are the grades.
  • Use sum to get the total of all grades, then divide by the number of grades to get the average.
n = int(input())
a = []
for i in range(n):
  name, *grades = input().split()
  a.append((name, round(sum(map(int, grades)) / len(grades))))
print(a)
Answered By: Unmitigated
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.