2011-03-20 67 views
1

我有一个模型,其中有一个属性可以跟踪价格。现在,我有一个特定模型的列表。无论如何,重新排列列表以按特定属性排序? python足够聪明地知道属性是一个可以排序的值吗?我没有跟踪使用数据库的特定模型的实例(这不是我需要的,因此我不能仅按照排序顺序从数据库中检索实例) 谢谢!如何根据某个类的特定属性进行排序?

+0

http://wiki.python.org/moin/HowTo/Sorting/ – eat 2011-03-20 09:08:04

回答

4

您可以使用内置的sorted功能,用它返回一个对象的价格定制的功能在一起:

class Dummy(object) : 
    pass 

def getPrice(obj) : 
    return obj.price 

d0 = Dummy() 
d0.price = 56. 
d1 = Dummy() 
d1.price=16. 

d2 = Dummy() 
d2.price=786. 

d3 = Dummy() 
d3.price=5.5 

elements = [d0, d1, d2, d3] 

print 'Pre-sorting:' 
for elem in elements : 
    print elem.price 

sortedElements = sorted(elements, key=getPrice) 

print 'Post-sorting:' 
for elem in sortedElements : 
    print elem.price 

这也将通过您的类的任何方法,返回的价格,例如工作

class Dummy(object) : 
    def __init__(self, price) : 
     self._price = price 
    def getPrice(self) : 
     return self._price 

... 

sortedElements = sorted(elements, key = Dummy.getPrice) 

更多见http://wiki.python.org/moin/HowTo/Sorting/

0

要在原地进行排序,您可以使用list.sort方法,该方法使用定义要排序的键的函数。

>>> class Data(object): 
...  def __init__(self,x,y): 
...    self.x=x 
...    self.y=y 
... 
>>> l=[Data(i,i+1) for i in xrange(10,-1,-1)] 
>>> print ", ".join("%s %s"%(x.x,x.y) for x in l) 
10 11, 9 10, 8 9, 7 8, 6 7, 5 6, 4 5, 3 4, 2 3, 1 2, 0 1 
>>> l.sort(key=lambda obj:obj.y) 
>>> print ", ".join("%s %s"%(x.x,x.y) for x in l) 
0 1, 1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9 10, 10 11 

再弄list,同时保持原来不变,使用sorted功能与类似定义可选key参数。

2

或者您可以使用“operator.attrgetter()”:

list_of_objects.sort(key=operator.attrgetter('name_of_attribute_to_sort_by')) 
0

最好的地方,看看是http://wiki.python.org/moin/HowTo/Sorting

个人,类__cmp__功能要容易上手得多带班打交道时,因为通常你总是想以同样的方式对它们进行排序。

下面是一些简单的例子:

class Foo : 
    def __init__(self, x, y) : 
     self.x = x 
     self.y = y 

    def __cmp__(self, x) : 
     return cmp(self.x, x) 

    def __repr__(self) : 
     return "Foo(%d)" % self.x 

# Simple list of objects 
data = [ 
    Foo(1, 99), 
    Foo(5, 94), 
    Foo(6, 93), 
    Foo(2, 97), 
    Foo(4, 95), 
    Foo(3, 96), 
] 

# sort using the __cmp__ class method - in numeric order 
print sorted(data) 

# sort using the key lambda, which reverse sorts... 
print sorted(data, key=lambda a : a.y) 
相关问题