sorting a list of objects related to their values

hi there,

got some problem sorting a list:

lets say we have a list of Objects(class instances)


class A():
  def __init__(self, value):
    self.value = value

list_ = [A(5), A(3), A(10)]


now i want to sort that list. the result should be [A(3), A(5), A(19)]. That means:


l_sorted = [i.value for i in list_]

l_sorted should then produce: [3,5,10]

But i dont need the list of integers, i need a list of the objects sorted by their values…:confused:

Any ideas ?

This used to work in Python 2.

newlist = sorted(objects, key = lambda i:i.value())

sorted() function takes a second argument (‘key’) which allows you to choose by what to determine the sorting.
“lambda” is a way to create a function in Python in one line. The syntax is kinda confusing, first “i” is the input (the current element of the list), “i.value” is the output (which is used for sorting). You could use an ordinary function, but that would take more lines.

some options:

Thanks Guys, just after writing the Question, i found the answer :slight_smile: in the web… i’ll give that a try.

edit:

While:


def main(cont):
    own = cont.owner
    self = ob['System']

    list_ = [Tile(51), Tile(60), Tile(1200)]
    list_.sort(key= lambda x:x.value)
    
    print ( list__ )

works fine, but:


list_sorted = list_.sort(key= lambda x:x.value)

returns None

:confused:

Why is that ? i need some copies of the list anyway, how can i achieve this ?