基于 python 中的两个变量排序
Sorting based on two variables in python
我正在Python中写一个排序算法。
例如,
假设我从 1 parent 生成了 10 child。
每个 child 有两个属性 "Fitness" 和 "Noise".
比方说,我先计算 10 children 的 "Fitness" 和 select 只有 3 个最好的 children(选择更高的 "fitness"尽可能)。例如,让我们将 60、50、40 作为 3 个最佳 children.
的适应度值
现在我开始计算3child仁的"noise"。再举个例子,假设我得到 3 children 的 "noise" 作为 5,8,6。 (越少 "noise" 被认为更好)。
如何根据最佳 "fitness" 和 "noise" 找到要选择的排序算法。理想情况下,我需要 child 高 "fitness" 和低 "noise"。我需要按照我从 3 children.child 中选出最好的 child 的方式对它们进行排序。
Initial 3 children:
Fitness {60,50,40} Noise {5,8,6}
我的理想3children排序后应该是:
Fitness {60,40,50} Noise {5,6,8}
我也不确定如何将 selecting 噪音的权重作为次要变量。
基本上我在python中寻找一个好的排序算法。
>>> 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)]
您可以使用内置的 sorted
函数,并传递一个 lambda 作为键。 lambda returns 用于比较的对象。如果我们 return 一个元组,它将根据元组的第一个元素排序,然后是第二个元素,依此类推
如果我们让元组首先是噪音,然后是适应度的负数,它会给出你想要的顺序:
>>> sorted(children, key=lambda child: (child.noise, -child.fitness))
[Child(fitness=60, noise=5),
Child(fitness=40, noise=6),
Child(fitness=50, noise=8)]
假设你有一个元组列表,其中每个元组代表两个属性 fitness 和 noise - [(10,5),(90,7),(100,12) ...]
,你可以使用下面的代码 -
>>> 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
我正在Python中写一个排序算法。
例如,
假设我从 1 parent 生成了 10 child。 每个 child 有两个属性 "Fitness" 和 "Noise".
比方说,我先计算 10 children 的 "Fitness" 和 select 只有 3 个最好的 children(选择更高的 "fitness"尽可能)。例如,让我们将 60、50、40 作为 3 个最佳 children.
的适应度值现在我开始计算3child仁的"noise"。再举个例子,假设我得到 3 children 的 "noise" 作为 5,8,6。 (越少 "noise" 被认为更好)。
如何根据最佳 "fitness" 和 "noise" 找到要选择的排序算法。理想情况下,我需要 child 高 "fitness" 和低 "noise"。我需要按照我从 3 children.child 中选出最好的 child 的方式对它们进行排序。
Initial 3 children:
Fitness {60,50,40} Noise {5,8,6}
我的理想3children排序后应该是:
Fitness {60,40,50} Noise {5,6,8}
我也不确定如何将 selecting 噪音的权重作为次要变量。
基本上我在python中寻找一个好的排序算法。
>>> 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)]
您可以使用内置的 sorted
函数,并传递一个 lambda 作为键。 lambda returns 用于比较的对象。如果我们 return 一个元组,它将根据元组的第一个元素排序,然后是第二个元素,依此类推
如果我们让元组首先是噪音,然后是适应度的负数,它会给出你想要的顺序:
>>> sorted(children, key=lambda child: (child.noise, -child.fitness))
[Child(fitness=60, noise=5),
Child(fitness=40, noise=6),
Child(fitness=50, noise=8)]
假设你有一个元组列表,其中每个元组代表两个属性 fitness 和 noise - [(10,5),(90,7),(100,12) ...]
,你可以使用下面的代码 -
>>> 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