如何按类的特定属性排序? [英] How to sort by a particular attribute of a class?

查看:112
本文介绍了如何按类的特定属性排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有跟踪价格的属性的模型。现在我有一个这个模型的列表。有没有办法重新排列列表按那个特定的属性排序? python是否足够聪明才能知道该属性是可以排序的值?我没有跟踪使用数据库的特定模型的实例(它不需要我正在做的,所以我不能只是按照排序顺序从数据库检索实例)
谢谢!

解决方案

您可以使用内置的排序的函数,以及定制函数它返回一个对象的价格:

  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

元素= [d0,d1,d2,d3]

打印'pre-sorting:'
元素中的元素
print elem.price

sortedElements = sorted(elements,key = getPrice)

print '排序后:'
对于elem在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/ 了解详情。 / p>

I have a model with an attribute which keeps track of the price. Right now, I have a list of that certain model. Is there anyway to rearrange the list to sort by that particular attribute? Is python smart enough to know that the attribute is a value which can be sorted? I am not keeping keeping track of the instances of a particular model using a database (it is not needed for what I am doing, so I cannot just retrieve the instances from the database in sorted order) Thanks!

解决方案

You can use the inbuilt sorted function, together with a custom-made function that returns the price of an object:

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

This would also work via any method of your class that returns the price, e.g.

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

...

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

See http://wiki.python.org/moin/HowTo/Sorting/ for more.

这篇关于如何按类的特定属性排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆