Sum of Values within Compound Lists

Asked

Viewed 76 times

2

I have a question about how to add certain values in Composite Lists. And I wanted to know that there is a quick method for this very.

lista_total = []
d = 0

while True:
    nome = str(input('Nome: '))
    lista_total.append(list())
    lista_total[d].append(nome)

    nota1 = int(input('Nota 1: '))
    lista_total[d].append(nota1)

    nota2 = int(input('Nota 2: '))
    lista_total[d].append(nota2)

    d += 1
    question = str(input('Quer continuar? [S/N] '))
 
    if question not in 'Ss':
        break

print('-=' * 30)
print('No. Nome          MÉDIA')
print('-' * 10)
for c in range(0, d):
    print(f'{c} ')      # Média ficará à frente de {c}

Output Example:

nº    Nome      Média
0     Ana       15.7
1     João      20.0
2     André     10.0

I wanted to know if you can take the "total list" and find the other index list 0 for example and add the values that are in indexes 1 and 2 (because 0 is the name of the supposed person) and then divide them by 2.

1 answer

2


First, you don’t need this index d. Just read the data and at the end you add everything in lista_total at once. Since the data are of different types (a name that is a string and several notes that are numbers), one usually uses tuples instead of lists (of course with lists also works, but when using tuples you already indicate - for anyone who moves the code, including yourself - that they may have data of different types there).

Anyway, to read the data, it could be like this:

lista_total = []
while True:
    nome = input('Nome: ')
    nota1 = int(input('Nota 1: '))
    nota2 = int(input('Nota 2: '))

    lista_total.append((nome, [nota1, nota2]))
    if input('Quer continuar? [S/N] ').lower() != 's':
        break

Note the parentheses of the expression (nome, [nota1, nota2]): this creates a tuple containing the name in the first position and the list with the notes in the second position. At first glance it may seem that these parentheses are redundant, but they are not. If you just lista_total.append(nome, [nota1, nota2]), would be passing 2 parameters to append (the name and the list of notes) and this would give error because append only takes one parameter. By placing these parentheses, I create the tuple, which is what will be inserted in the list.

In the end, lista_total will have several tuples, and each of these tuples will have the name in the first position and the list of notes in the second.

Note also that input already returns a string, so no need to do str(input(etc...)), is redundant and unnecessary. Finally, I used lower() to turn the "Want to continue" option into lower case, so you just need to compare it with 's'.


Then to print, just use enumerate to browse the list along with the indexes. Then, for each tuple in the list, take the first element (which will be the name), and the second (the list with the notes) and print the information. To calculate the average, simply divide the sum of the notes (using sum) by quantity (using len, that picks up the list size):

print('-=' * 15)
alinhamento = '{:<5}{:<20}{}'
print(alinhamento.format('nº','Nome', 'Média'))
print('-' * 30)
for i, dados in enumerate(lista_total):
    notas = dados[1]
    print(alinhamento.format(i, dados[0], sum(notas) / len(notas))) 

I also used the formatting options to align the data: <5 right align with 5 positions (filling unused positions with spaces), and <20 right align with 20 positions (adjust the values according to what you need). Example:

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
nº   Nome                Média
------------------------------
0    Fulano de tal       3.5
1    Ciclano de qual     5.5

If you want, you can already "dismember" the tuple into variables in itself for:

for i, (nome, notas) in enumerate(lista_total):
    print(alinhamento.format(i, nome, sum(notas) / len(notas))) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.