python - 需要帮助按键对对象列表进行排序

标签 python list sorting key genetic-algorithm

我无法获取此代码来使用 .sort() 或sorted() 对对象列表进行排序。我在这里缺少什么?

附注如果有人有任何建议,我的solution.distance()方法也可以使用一些整容手术。

谢谢!

import random
import math

POPULATION_SIZE = 100

data = [[1, 565.0, 575.0],
        [2, 25.0, 185.0],
        [3, 345.0, 750.0],
        [4, 945.0, 685.0],
        [5, 845.0, 655.0],
        [6, 880.0, 660.0],
        [7, 25.0, 230.0],
        [8, 525.0, 1000.0],
        [9, 580.0, 1175.0],
        [10, 650.0, 1130.0]
        ]

class Solution():

  def __init__(self):
    self.dna = []
    self.randomize()

  def randomize(self):
    temp = data[:]
    while len(temp) > 0:
      self.dna.append( temp.pop( random.randint( 0,len(temp)-1 ) ) ) 

  def distance(self): 
    total = 0 
    #There has to be a better way to access two adjacent elements.
    for i, points in enumerate(self.dna):
      if i < (len(self.dna)-1): 
        total += math.sqrt( (points[1]-self.dna[i+1][1])**2 + (points[2]-self.dna[i+1][2])**2 )
      else:
        total += math.sqrt( (points[1]-self.dna[0][1])**2 + (points[2]-self.dna[0][2])**2 )
    return int(total)


class Population():

  def __init__(self):
    self.solutions = []
    self.generation = 0

    #Populate with solutions
    self.solutions = [Solution() for i in range(POPULATION_SIZE)]


  def __str__(self):

    result = ''

    #This is the part that is not returning sorted results.  I tried sorted() too.
    self.solutions.sort(key=lambda solution: solution.distance, reverse=True)


    for solution in self.solutions:
      result += 'ID: %s - Distance: %s\n' % ( id(solution),  solution.distance() )

    return result


if __name__ == '__main__':

  p = Population()
  print p

最佳答案

改变

key=lambda solution: solution.distance

key=lambda solution: solution.distance()

(调用该函数需要括号。)

或者,您可以将 distance 方法设为属性:

  @property
  def distance(self): 
      ....

在这种情况下,将所有出现的 solution.distance() 更改为 solution.distance。我认为这个替代解决方案更好一点,因为每次您想谈论距离时,它都会消除两个困惑的字符(括号)。

PS。 key=lambda 解决方案:solution.distanceself.solutions 中的每个 solution 返回绑定(bind)方法 solution.distance >。由于相同的对象作为每个解决方案的键返回,因此没有发生所需的排序。

关于python - 需要帮助按键对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3196112/

相关文章:

python - 为 webdesigner 设置 Django 的最小工作量

python - 出错时自动启动 python 调试器

Python pipe.send() 在 Mac OS 上挂起

c# - List<string> C# 自定义排序。数字后加下划线

python - 检查排列是否存在/组合是否唯一

java - 修饰符 static 只允许在常量变量声明中使用

python - 如何访问二维列表中的元组

c# - 将列表与 C# 中的一个或多个列表 : how to specify at what index are they located in the first list? 进行比较

algorithm - 这个 "incremental sort"的时间复杂度

c++ - Qt:交换 QGraphicsRectItem 位置的最佳方法是什么