Finding attributes in a list
Marcus Goldfish
magoldfish at gmail.com
Sat Apr 2 23:44:11 EST 2005
> class Player(object):
> def __init__(self, **kw): self.__dict__.update(kw)
> def __repr__(self): return '<Player %s>'%getattr(self, 'name', '(anonymous)')
>
> import operator
> [p.name for p in sorted(players, key=operator.attrgetter('attacking'), reverse=True)]
Just happened to read this thread and wanted to say this is a neat
little example-- thank you! I have a couple of followup questions.
(1) Is there a performance penalty for using key=operator.attrgetter()?
(2) The Player class looks like a nice model for a data table when one
wants to sort by arbitrary column. Would you agree?
(3) Suppose one wished to construct a player list from a collection of
attribute lists, e.g.,
names = ['bob', 'sam', 'linda']
attack = [7, 5, 8]
defense = [6, 8, 6]
# construct players list here
Can you recommend an efficient way to construct the player list?
Thanks!
Marcus
More information about the Python-list
mailing list