Finding attributes in a list

infidel saint.infidel at gmail.com
Tue Mar 29 12:19:47 EST 2005


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']
>>>




More information about the Python-list mailing list