lambda vs. operator.attrGetter('xxx') as sort key in Python

Posted by Paul McGuire on Stack Overflow See other posts from Stack Overflow or by Paul McGuire
Published on 2010-04-24T15:56:37Z Indexed on 2010/04/24 16:03 UTC
Read the original article Hit count: 161

Filed under:
|
|
|
|

I am looking at some code that has a lot of sort calls using comparison functions, and it seems like it should be using key functions.

If you were to change seq.sort(lambda x,y: cmp(x.xxx, y.xxx)), which is preferable:

seq.sort(key=operator.attrgetter('xxx'))

or:

seq.sort(key=lambda a:a.xxx)

I would also be interested in comments on the merits of making changes to existing code that works.

© Stack Overflow or respective owner

Related posts about python

Related posts about sort