在其中一个项值上对项目进行排序的最佳方法是什么

时间:2010-08-17 15:02:55

标签: python

我在列表中有两个对象实例

class Thing():
     timeTo = 0
     timeFrom = 0
     name = ""

o1 = Thing()
o1.name = "One"
o1.timeFrom = 2

o2 = Thing()
o2.timeTo = 20
o2.name = "Two"

myList = [o1, o2]


biggestIndex = (myList[0].timeFrom < myList[1].timeTo) & 1
bigger  = myList.pop(biggestIndex)
lesser  = myList.pop()

print bigger.name
print lesser.name

o1和o2都有两个属性,我想比较列表中的第一个timeFrom属性和第二个属性timeTo属性。

我觉得这有点尴尬和奇怪,是否有更好更可读的方法呢?

3 个答案:

答案 0 :(得分:2)

最佳解决方案是使Thing个实例可排序。您可以通过实施__lt__

来实现这一目标
class Thing():
     timeTo = 0
     timeFrom = 0
     name = ""

     def __lt__(self, other):
         return self.timeFrom < other.timeTo


lesser, bigger = sorted(myList)

Python2有lesser, bigger = sorted(myList, cmp=lambda one,other: one.timeFrom < other.timeTo)

在Python3 cmp消失了,我想强迫人们去做(或学习)OOP并写一个 adapter

class SortAdaper(object):
    def __init__(self, obj ):
        self.obj = obj

class TimeLineSorter(SortAdaper):
    """ sorts in a timeline """
    def __lt__(self, other):
        return self.obj.timeFrom < other.obj.timeTo

class NameSorter(SortAdaper):
    """ sorts by name """
    def __lt__(self, other):
        return self.obj.name < other.obj.name

print sorted( myList, key=TimeLineSorter)
print sorted( myList, key=NameSorter)

答案 1 :(得分:1)

请参阅attrgetter

import operator

getter = operator.attrgetter('timeFrom')

bigger = max(myList, key=getter)  
lesser = min(myList, key=getter)

print bigger.name  
print lesser.name

编辑:

attrgetter 也需要排序或需要功能的任何地方。

lesser, bigger = sorted(myList, key=getter)

答案 2 :(得分:0)

如果对象只能有一个时间值,我会这样做:

class Thing(object):
    def __init__(self, name, time = 0, timename = 'to'):
        self.name, self.time, self.timename = (name,time,timename)

    def __repr__(self):
        return "Thing(%r, %i, %r)" % (self.name, self.time, self.timename)

    def __lt__(self, other):
        return self.time < other.time

o1 = Thing("One", 5, 'from')

o2 = Thing("Two", 20, 'to')

myList = [o1, o2]

print myList
print max(myList)
print min(myList)