Sorting and list comprehension
Alex Martelli
aleaxit at yahoo.com
Tue Oct 12 03:17:13 EDT 2004
Tran Tuan Anh <anhtt at hotmail.com> wrote:
> Hi all,
>
> I would like to do the followings, but I am quite new to Python hence
> have not figured it out how...
>
> salary = dictionary
> salary["Bob"] = 11
> salary["Marry"] = 4
> salary["me"]= 45
>
> How can I have a sort_value() function acts like this:
> result = sortvalue(salary)
> result = ["Marry","Bob","me"]
You could upgrade to Python 2.4 and define
def sortvalue(d):
return sorted(d, key=d.get)
(or code it inline). If you're stuck with Python 2.3,
def sortvalue(d):
aux = [ (v,k) for k, v in d.iteritems() ]
aux.sort()
return [ k for v, k in aux ]
is probably the best you can do.
> Regarding the list construction, how can I do this:
>
> list = [item for item in list1 if for all item2 in list2 NOT
> bad_condition(item, item2]
One possibility (I think it's not that good...):
from itertools import ifilter, imap
[x for x in list1
if 23 not in imap(lambda x: 23,
ifilter(lambda y: not badcondition(x, y), list2))
]
I think it's too fancy and you should define an auxiliary function:
def itemisok(item, list2, bad_condition):
for y in list2:
if bad_condition(item, y): return False
return True
so that you can code
[x for x in list1 if itemisok(x, list2, bad_condition)]
or thereabouts...
Alex
More information about the Python-list
mailing list