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
--
http://mail.python.org/mailman/listinfo/python-list