Finding attributes in a list
Steven Bethard
steven.bethard at gmail.com
Tue Mar 29 13:29:33 EST 2005
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']
STeVe
More information about the Python-list
mailing list