Finding attributes in a list

Bengt Richter bokr at oz.net
Tue Mar 29 20:13:02 EST 2005


On Tue, 29 Mar 2005 11:29:33 -0700, Steven Bethard <steven.bethard at gmail.com> wrote:

>infidel wrote:
>> You can use the new 'sorted' built-in function and custom "compare"
>> functions to return lists of players sorted according to any criteria:
>> 
>> 
>>>>>players = [
>> 
>> ... 	{'name' : 'joe', 'defense' : 8, 'attacking' : 5, 'midfield' : 6,
>> 'goalkeeping' : 9},
>> ... 	{'name' : 'bob', 'defense' : 5, 'attacking' : 9, 'midfield' : 6,
>> 'goalkeeping' : 3},
>> ... 	{'name' : 'sam', 'defense' : 6, 'attacking' : 7, 'midfield' : 10,
>> 'goalkeeping' : 4}
>> ... ]
>> 
>>>>>def cmp_attacking(first, second):
>> 
>> ... 	return cmp(second['attacking'], first['attacking'])
>> ...
>> 
>>>>>[p['name'] for p in sorted(players, cmp_attacking)]
>> 
>> ['bob', 'sam', 'joe']
>
>Or more efficiently, use the key= and reverse= parameters:
>
>py> players = [
>... 	dict(name='joe', defense=8, attacking=5, midfield=6),
>... 	dict(name='bob', defense=5, attacking=9, midfield=6),
>... 	dict(name='sam', defense=6, attacking=7, midfield=10)]
>py> import operator
>py> [p['name'] for p in sorted(players,
>...                            key=operator.itemgetter('attacking'),
>...                            reverse=True)]
>['bob', 'sam', 'joe']
>
Perhaps the OP doesn't yet realize that Python also provides the ability
to define custom classes to represent players etc. E.g., using instance attribute
dicts instead of raw dicts (to save typing ;-):

 >>> class Player(object):
 ...     def __init__(self, **kw): self.__dict__.update(kw)
 ...     def __repr__(self): return '<Player %s>'%getattr(self, 'name', '(anonymous)')
 ...
 >>> players = [
 ...     Player(name='joe', defense=8, attacking=5, midfield=6),
 ...     Player(name='bob', defense=5, attacking=9, midfield=6),
 ...     Player(name='sam', defense=6, attacking=7, midfield=10)]
 >>> players
 [<Player joe>, <Player bob>, <Player sam>] 
 >>> import operator
 >>> [p.name for p in sorted(players, key=operator.attrgetter('attacking'), reverse=True)]
 ['bob', 'sam', 'joe']

And then he could create a Team class which might have players as an internal list,
and provide methods for modifying the team etc., and generating various reports
or calculating and/or retrieving data. Not to mention properties for dynamically
caclulated attributes etc ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list