|
Re: The fate of reduce() in Python 3000
|
Posted: Nov 3, 2007 8:25 PM
|
|
> I have a list of some records. With lambda I can do: > > my_list.sort(key = lambda x: x.name) > # or > my_list.sort(key = lambda x: x.age) > # or > my_list.sort(key = lambda x: x.address) > > Can I sort list by different keys very easy without lambda?
I think you'll have to define nested functions just prior to calling sort with the key argument. Without lambda, it just can't be done anonymously. The alternative is to make your own python extension that implements sort differently. If sort was implemented so as to order one list (data) according to the default ordering of a second list (keys), then you could avoid the need for lambda altogether when performing custom sort operations. Below is an example I entered into the python command-line interpreter.
[formwalt@transport:~] # python Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def fn(): ... def fn_name_key(x): ... return x['name'] ... def fn_age_key(x): ... return x['age'] ... def fn_address_key(x): ... return x['address'] ... bob = {'name':'Bob','age':23,'address':'somewhere'} ... alice = {'name':'Alice','age':54,'address':'nowhere'} ... phil = {'name':'Phil','age':30,'address':'unknown'} ... my_list = [bob,alice,phil] ... print "Original List: " + str(my_list) ... my_list.sort(key = fn_name_key) ... print "Sorted by Name: " + str(my_list) ... my_list.sort(key = fn_age_key) ... print "Sorted by Age: " + str(my_list) ... my_list.sort(key = fn_address_key) ... print "Sorted by Address: " + str(my_list) ... >>> fn() Original List: [{'age': 23, 'name': 'Bob', 'address': 'somewhere'}, {'age': 54, 'name': 'Alice', 'address': 'nowhere'}, {'age': 30, 'name': 'Phil', 'address': 'unknown'}] Sorted by Name: [{'age': 54, 'name': 'Alice', 'address': 'nowhere'}, {'age': 23, 'name': 'Bob', 'address': 'somewhere'}, {'age': 30, 'name': 'Phil', 'address': 'unknown'}] Sorted by Age: [{'age': 23, 'name': 'Bob', 'address': 'somewhere'}, {'age': 30, 'name': 'Phil', 'address': 'unknown'}, {'age': 54, 'name': 'Alice', 'address': 'nowhere'}] Sorted by Address: [{'age': 54, 'name': 'Alice', 'address': 'nowhere'}, {'age': 23, 'name': 'Bob', 'address': 'somewhere'}, {'age': 30, 'name': 'Phil', 'address': 'unknown'}] >>>
|
|