Sorting and list comprehension

Peter Otten __peter__ at web.de
Sun Oct 10 11:27:50 CEST 2004


Tran Tuan Anh 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"]
> 
> In sort, I would like to sort the key according to the values.

>>> def sorted(items, key):
...     tmp = [(key(v), i, v) for (i, v) in enumerate(items)]
...     tmp.sort()
...     return [v[2] for v in tmp]
...
>>> salary = dict(Bob=11, Mary=4, me=45)
>>> result = sorted(salary, key=salary.__getitem__)
>>> result
['Mary', 'Bob', 'me']

Python 2.4 will have a similar sorted() function as a builtin.

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

I would use a conventional loop:

>>> list1 = [1, 2, 3, 4]
>>> list2 = [6, 2]
>>> result = []
>>> def bad_condition(a, b):
...     return a*2 == b
...
>>> for item1 in list1:
...     for item2 in list2:
...             if bad_condition(item1, item2):
...                     break
...     else:
...             result.append(item1)
...
>>> result
[2, 4]

By contrast, the listcomp solution is messy and does no short-circuiting:

>>> [item1 for item1 in list1 if True not in [bad_condition(item1, item2)
for item2 in list2]]
[2, 4]

Peter




More information about the Python-list mailing list