Sort class list in Python

Asked

Viewed 275 times

1

I have a class defined as follows::

class Cromossomo():
    def __init__(self, cromossomo, comprimento):    #Construtor
        self.cromossomo = cromossomo 
        self.comprimento = comprimento

From it I have a list of the class Chromosome. called final list.

I want to sort that list by length, from the largest to the smallest. I tried using Sort, Sorted, but I couldn’t.

For example:

def ordenar(lista_final):
    sorted(lista_final, key=attrgetter('comprimento'), reverse=True)


ordenar(lista_final)

How do I make it work?

  • This final list is composed of?

  • chromosome attribute and length ex: lista_final[0]. chromosome = [1,0,0,1] lists_final[0]. length = 25 I want to sort by length

1 answer

3


You did almost everything right, just in time to set the key to sorting you got confused:

#Classe definida pelo AP
class Cromossomo():
    def __init__(self, cromossomo, comprimento):    #Construtor
        self.cromossomo = cromossomo 
        self.comprimento = comprimento
    
#Cria uma lista de teste
genoma = [Cromossomo(1,20), Cromossomo(2,10), Cromossomo(3,33), Cromossomo(4,2), Cromossomo(5,21), Cromossomo(6,30)]

#Ordena a lista baseada no comprimento do maior para o menor
genoma_ordenado = sorted(genoma, key=lambda x: x.comprimento,reverse=True)

#Imprime apenas os comprimentos da lista já ordenada
print([cromossomo.comprimento for cromossomo in genoma_ordenado])

Code working in Repl.it: https://repl.it/repls/FamiliarCrimsonMp3

Addendum:

As mentioned in the comments the AP did not commit coding errors it got confused and forgot to make an import, implying in another output for correcting the code that would import the function attrgette() module operator.

from operator import attrgetter
  • Thank you very much!

  • 2

    Just to let the record that there was nothing wrong with the AP code, he probably forgot to import the function attrgetter. I modified your example to demonstrate. I leave here as a complement.

  • No doubt, so much so that I didn’t say that he made a mistake and yes "got confused"

Browser other questions tagged

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