Help in python Lists

Asked

Viewed 108 times

1

Good night I’m having a hard time with this:

[['1', 0.0, 1.8], ['1', 3.0, 2.0], ['1', 5.0, 1.5], ['1', 6.0, 1.5], ['1', 9.0, 3.0], ['2', 0.0, 1.8], ['2', 1.0, 1.5], ['2', 2.0, 1.5], ['2', 3.0, 2.0], ['2', 8.0, 2.1], ['3', 0.0, 1.8], ['3', 1.0, 2.0], ['3', 4.0, 1.5], ['3', 8.0, 1.5], ['3', 9.0, 1.5], ['4', 0.0, 1.8], ['4', 1.0, 1.5], ['4', 2.0, 2.0], ['4', 3.0, 2.0], ['4', 4.0, 2.0]]

I want to find the values of the equal rows and find the arithmetic medias of the other two values..

the output of my code should be like this

[['1',4.6,1.96],['2',2.8,1.78],['3',4.4,1.66],['4',2,1.86]]

for example for the values of fila[0]==1, to find the average of these values should be added the values (0.0+3.0+5.0+6.0+9.0) and divide them by the amount of them,5. I cannot properly traverse this matrix to make the right condition to find the result matrix...

I went to the first list with this code but I can only find the medias of the valuables that contain as the first element to str '1'...

suma = 0

lista2=[]

for n in range (len(lista)-1):

    if lista[n][0]==lista[n][0]:

        lista2.append(lista[n][0])

        suma= suma+lista[n][1]

    if lista[n][0]!=lista[n+1][0]:

        break

print (suma)

#print(len(lista2))

print(suma/len(lista2))
  • it has to be that way?

  • yes the result has to be in the form of lists again, ie as a matrix...

2 answers

0

Different from what you were using for, my suggestion is to use the pandas that already has some functions that will facilitate your work. follows an example of how the code would look. at the end it returns the list

import pandas as pd


l = [['1', 0.0, 1.8], ['1', 3.0, 2.0], ['1', 5.0, 1.5], ['1', 6.0, 1.5], ['1', 9.0, 3.0], ['2', 0.0, 1.8], ['2', 1.0, 1.5], ['2', 2.0, 1.5], ['2', 3.0, 2.0], ['2', 8.0, 2.1], ['3', 0.0, 1.8], ['3', 1.0, 2.0], ['3', 4.0, 1.5], ['3', 8.0, 1.5], ['3', 9.0, 1.5], ['4', 0.0, 1.8], ['4', 1.0, 1.5], ['4', 2.0, 2.0], ['4', 3.0, 2.0], ['4', 4.0, 2.0]]

df = pd.DataFrame(data=l)

df = df.groupby([0]).mean()

df = df.reset_index()

df[2] = df[2].apply(lambda x : float("%.2f" %x))

listaFinal = df.values.tolist()

print(listaFinal)

0


The test you did makes no sense:

if lista[n][0]==lista[n][0]:

This condition checks whether the element is equal to itself, which it will always be. When it if lista[n][0]!=lista[n+1][0]: You’re assuming that the same elements are always followed, and if they’re not, it wouldn’t work either. Also do not remove duplicates and make an invalid comparison when in the last element.

One solution to your problem is to group the values based on the first position of each element for a dictionary. After grouping calculates the medias of each and can use this dictionary or convert back to a list.

Example:

lista = [['1', 0.0, 1.8], ['1', 3.0, 2.0], ['1', 5.0, 1.5], ['1', 6.0, 1.5], ['1', 9.0, 3.0], ['2', 0.0, 1.8], ['2', 1.0, 1.5], ['2', 2.0, 1.5], ['2', 3.0, 2.0], ['2', 8.0, 2.1], ['3', 0.0, 1.8], ['3', 1.0, 2.0], ['3', 4.0, 1.5], ['3', 8.0, 1.5], ['3', 9.0, 1.5], ['4', 0.0, 1.8], ['4', 1.0, 1.5], ['4', 2.0, 2.0], ['4', 3.0, 2.0], ['4', 4.0, 2.0]]

agrupadas = {}
for elem in lista:
    fila = elem[0]
    if fila in agrupadas: # se já existe no dicionario acrescenta os numeros
        agrupadas[fila][1].append(elem[1])
        agrupadas[fila][2].append(elem[2])
    else: # se não existe cria uma nova entrada
        agrupadas[fila] = [fila, [elem[1]], [elem[2]]]

resultado = []
for item in agrupadas.values():
    # acrescenta o elemento à lista de resultado com os cálculos das médias
    resultado.append([item[0], sum(item[1])/len(item[1]), sum(item[2])/len(item[2])])

print(resultado)

Upshot:

[['1', 4.6, 1.9600000000000002], ['2', 2.8, 1.78], ['3', 4.4, 1.6600000000000001], ['4', 2.0, 1.86]]

Check it out at Ideone

The reason why 1.9600000000000002 appears instead of 1.96 has to do with the lack of precision in the representation of floating comma values, such as 0.1. There are already several questions here on the site on this topic, which I suggest reading:

For your case maybe you wanted to round to two decimal places or just show the value with two decimal places when you present it on the way out.

Browser other questions tagged

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