需要帮助按键排序对象列表吗

2024-04-20 07:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法让此代码使用.sort()或sorted()对对象列表进行排序。我错过了什么?在

p.S.我的解决方案.距离()如果有人有什么建议,也可以做一些整容手术。在

谢谢!在

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

Tags: inselfforlendefmathresulttemp
3条回答

下面是在distance()中编写循环的更好方法:在代码中放入来自itertools documentation的以下函数定义:

from itertools import izip, tee
def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

然后,您可以编写distance来利用Python高效的迭代器操作例程,如下所示:

^{pr2}$

即使dna数组很长,这应该是相当有效的。在

下面尝试使用函数式编程技术清理类:

import random

class Solution():

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

  def randomize(self):
    self.dna = data
    random.shuffle(self.dna)

  def distance(self):
    # Return the distance between two points.
    def point_distance((p1, p2)):
      return math.sqrt((p1[1]-p2[1])**2) + (p1[2]-p2[2])**2)
    # sums the distances between consecutive points.
    # zip pairs consecutive points together, wrapping around at end.
    return int(sum(map(point_distance, zip(self.dna, self.dna[1:]+self.dna[0:1])))

这是未经测试,但应该接近工作。另外,建议对数据使用类而不是3元素列表。为了使代码更清晰:

^{pr2}$

改变

key=lambda solution: solution.distance

^{pr2}$

调用所需的函数(括号)

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

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

在本例中,将solution.distance()的所有出现更改为solution.distance。我认为这个替代方案更好一些,因为每次你想谈论距离时,它都会消除两个混乱字符(parens)。在

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

相关问题 更多 >