Nic*_*ant 724 python sorting oop list count
我有一个Python对象列表,我想根据对象本身的属性进行排序.该列表如下:
>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,
<Tag: aes>, <Tag: ajax> ...]
Run Code Online (Sandbox Code Playgroud)
每个对象都有一个计数:
>>> ut[1].count
1L
Run Code Online (Sandbox Code Playgroud)
我需要按递减计数的数量对列表进行排序.
我已经看过几种方法,但我正在寻找Python的最佳实践.
Tri*_*ych 1196
# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)
# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)
Run Code Online (Sandbox Code Playgroud)
更多按键排序»
tzo*_*zot 80
可以使用最快的方法,特别是如果您的列表包含大量记录operator.attrgetter("count")
.但是,这可能会在运行前版本的Python上运行,因此拥有一个回退机制会很不错.您可能想要执行以下操作,然后:
try: import operator
except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda
ut.sort(key=keyfun, reverse=True) # sort in-place
Run Code Online (Sandbox Code Playgroud)
Jos*_*dal 59
读者应该注意到key =方法:
ut.sort(key=lambda x: x.count, reverse=True)
Run Code Online (Sandbox Code Playgroud)
比向对象添加丰富的比较运算符要快许多倍.我很惊讶地读到了这篇文章("果壳里的Python"第485页).您可以通过在这个小程序上运行测试来确认这一点:
#!/usr/bin/env python
import random
class C:
def __init__(self,count):
self.count = count
def __cmp__(self,other):
return cmp(self.count,other.count)
longList = [C(random.random()) for i in xrange(1000000)] #about 6.1 secs
longList2 = longList[:]
longList.sort() #about 52 - 6.1 = 46 secs
longList2.sort(key = lambda c: c.count) #about 9 - 6.1 = 3 secs
Run Code Online (Sandbox Code Playgroud)
我的非常小的测试表明,第一种测试速度慢了10倍,但该书说它一般只慢了约5倍.他们说的原因是由于python(timsort)中使用的高度优化的排序算法.
但是,非常奇怪的是.sort(lambda)比普通的旧.sort()更快.我希望他们解决这个问题.
小智 36
from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)
Run Code Online (Sandbox Code Playgroud)
jpp*_*jpp 36
面向对象的方法
最好的做法是使对象排序逻辑(如果适用)成为类的属性,而不是在每个实例中包含所需的顺序.
这可确保一致性并消除对样板代码的需求.
至少,您应该为此指定__eq__
和__lt__
操作.然后就用吧sorted(list_of_objects)
.
class Card(object):
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
def __lt__(self, other):
return self.rank < other.rank
hand = [Card(10, 'H'), Card(2, 'h'), Card(12, 'h'), Card(13, 'h'), Card(14, 'h')]
hand_order = [c.rank for c in hand] # [10, 2, 12, 13, 14]
hand_sorted = sorted(hand)
hand_sorted_order = [c.rank for c in hand_sorted] # [2, 10, 12, 13, 14]
Run Code Online (Sandbox Code Playgroud)
muh*_*huk 15
它看起来很像Django ORM模型实例的列表.
为什么不像这样对查询进行排序:
ut = Tag.objects.order_by('-count')
Run Code Online (Sandbox Code Playgroud)
如果要排序的属性是property,则可以避免导入operator.attrgetter
并使用该属性的fget
方法。
例如,对于Circle
具有属性的类,radius
我们可以circles
按半径对列表进行排序,如下所示:
result = sorted(circles, key=Circle.radius.fget)
Run Code Online (Sandbox Code Playgroud)
这不是最著名的功能,但经常为我节省导入的一行。
归档时间: |
|
查看次数: |
476127 次 |
最近记录: |