Sorting a List of Objects by an Attribute of the Objects Case-Insensitively
David Harrison
dave.l.harrison at gmail.com
Tue Apr 8 23:26:28 EDT 2008
On 09/04/2008, Jason <elgrandchignon at gmail.com> wrote:
> 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!
You're probably looking for the built-in function sorted,
e.g.
class Foo:
def __init__(self, value):
self.value = value
def __repr__(self):
return self.value
a = [Foo('c'), Foo('B'), Foo('A')]
print sorted(
a,
cmp=lambda x,y: cmp(x.lower(), y.lower()),
key=lambda x: x.value
)
More information about the Python-list
mailing list