By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,048 Members | 1,066 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,048 IT Pros & Developers. It's quick & easy.

Sorting a List of Objects by an Attribute of the ObjectsCase-Insensitively

P: n/a
Hi folks--

Basically, I have a pressing need for a combination of 5.2 "Sorting a
List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects
by an Attribute of the Objects" from the Python Cookbook.

My first guess isn't working:

import operator
def sort_by_attr(seq, attr):
key=operator.attrgetter(attr)
key=str.lower
return sorted(seq, key)

....would much appreciate any guidance!
Apr 9 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Apr 9, 4:04 am, Jason <elgrandchig...@gmail.comwrote:
Hi folks--

Basically, I have a pressing need for a combination of 5.2 "Sorting a
List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects
by an Attribute of the Objects" from the Python Cookbook.

My first guess isn't working:

import operator
def sort_by_attr(seq, attr):
key=operator.attrgetter(attr)
key=str.lower
return sorted(seq, key)

...would much appreciate any guidance!
HiJason,
Try key= lambda x: x.attr.lower()
The above should calculate the key only once for the items to be
sorted rather than using cmp which calculates more than that.

- Paddy.
Apr 9 '08 #2

P: n/a
Thanks so much everyone! That works great, & (presumably) is way
faster than the way I was doing it--
Apr 9 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.