Sorting based on two variables in python

2.3k views Asked by At

I am writing a sorting algorithm in Python.

For example,

Lets say I have 10 child generated from 1 parent. Each child has two attributes "Fitness" and "Noise".

Lets say, I calculate the "Fitness" for 10 children first and select only the 3 best children (higher "fitness" are chosen as best). For example let us take 60,50,40 as fitness values for the 3 best children.

Now I proceed to calculate the "noise" of the 3 children. Again for example, lets assume I get the "noise" for 3 children as 5,8,6. (Less "noise" is considered better).

How do I find a sorting algorithm to choose based on best "fitness" and "noise". I would ideally require a child with high "fitness" and low "noise". I would need to sort them in a way I take the best child out of 3 children.

Initial 3 children:

Fitness {60,50,40} Noise {5,8,6}

My Ideal 3 children after sorting should be:

Fitness {60,40,50} Noise {5,6,8}

I am also not sure how to give the weighting for selecting noise as a secondary variable.

Basically I am looking for a good sorting algorithm in python.

2

There are 2 answers

0
Peter Wood On BEST ANSWER
>>> from collections import namedtuple

>>> Child = namedtuple('Child', 'fitness noise')

>>> children = [Child(fitness=60, noise=5),
...             Child(fitness=50, noise=8),
...             Child(fitness=40, noise=6)]

You can use the builtin sorted function, and pass a lambda as the key. The lambda returns the object used for comparison. If we return a tuple, it will sort based on the first element of the tuple, then the second, etc.

If we make the tuple first be the noise, then the negative of the fitness, it will give the order you want:

>>> sorted(children, key=lambda child: (child.noise, -child.fitness))
[Child(fitness=60, noise=5),
 Child(fitness=40, noise=6),
 Child(fitness=50, noise=8)]
0
Utsav T On

Assuming you have a list of tuples, where each tuple represents the two attributes fitness and noise - [(10,5),(90,7),(100,12) ...], you can use the following piece of code -

>>> l = [(100,5),(89,13),(102,65),(10,3),(109,45)]
>>> l.sort(key = lambda x:x[0], reverse = True) ## Sorting(descending) on the basis of fitness
>>> l_ = l[:3]                                  ## Extract the top 3 tuples
>>> l_.sort(key = lambda x:x[1])                ## Sorting on the basis of noise