sort the list
Daniel Schüle
uval at rz.uni-karlsruhe.de
Mon Nov 21 08:16:43 EST 2005
[...]
>> >>> lst = [[1,4],[3,9],[2,5],[3,2]]
>> >>> lst
>>[[1, 4], [3, 9], [2, 5], [3, 2]]
>> >>>
>> >>>
>> >>> lst.sort(cmp = lambda x,y: cmp(x[1], y[1]))
>> >>> lst
>>[[3, 2], [1, 4], [2, 5], [3, 9]]
>> >>>
>>
>>works for Python 2.4
>>in earlier Pythons just let cmp = .. away
>>
>>Regards, Daniel
>
> what does let cmp = .. away mean?
it means
lst.sort(lambda x,y: cmp(x[1], y[1]))
I can offer you some more brain food to digest ;)
maybe you can adapt this solution, but that depends
on your problem
I find it clear and I used it recently
>>> name, age, salary = "name", "age", "salary"
>>> people = [
... {name:"oliver", age:25, salary:1800},
... {name:"mischa", age:23, salary:0},
... {name:"peter", age:22, salary:1500},
... ]
>>>
>>> def cmpFabrik(field):
... def cmpFunc(x,y):
... return cmp(x[field], y[field])
... return cmpFunc
>>> people.sort(cmp = cmpFabrik(name))
>>> people.sort(cmp = cmpFabrik(age))
>>> people.sort(cmp = cmpFabrik(salary))
it's not very OO but sometimes things are simple
and no need to create a class
Regards, Daniel
More information about the Python-list
mailing list