Saturday, 5 January 2019

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

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.



from lambda vs. operator.attrgetter('xxx') as sort key function in Python

No comments:

Post a Comment