I'm seeking advice on doing the following in a more pythonic way.
Consider:
class MyObj(object):
def __init__(self):
self.dict_properties = {}
Suppose I've got a list which contains multiple MyObj instances:
mylist = [<__main__.MyObj object at 0x1005e3b90, ...]
Now i want to sort mylist
开发者_JAVA技巧based on the value of a certain key in dict_properties
in MyObj.
What does work is:
mylist.sort(lambda x,y: cmp(x.dict_properties['mykey'],
y.dict_properties['mykey']))
but that hardly feels pythonic.
Is there a better way (perhaps using operator.attrgetter
)?
mylist.sort(key=lambda x: x.dict_properties['mykey'])
is way simpler, and faster. You could reach for operator
and try to compose an attrgetter
and an itemgetter
, but a straightforward lambda
(or def
) seems simplest here.
I'd just do:
mylist.sort(key=lambda o: o.dict_properties["kykey"])
You could also overide cmp on the class.
If speed is an issue, then use decorate-sort-undecorate:
mylist_decorated = [(elem.dict_properties['mykey'], elem) for elem in mylist]
mylist_decorated.sort()
mylist = [elem[1] for elem in mylist_decorated] # or zip(*mylist_decorated)[1] :)
- this way sort() can spread its wings.
精彩评论