list comprehensions: sorting?
Clark C . Evans
cce at clarkevans.com
Thu Sep 6 15:31:58 EDT 2001
On Thu, Sep 06, 2001 at 09:52:08AM +0200, Alex Martelli wrote:
| > As an SQL junkie... I've gotten addicted to
| > list comprehensions over a list of tuples...
| >
| > [process(x) for x in mylist if x[4]
| >
| > I read the above as something like...
| >
| > SELECT process(x) FROM mylist AS x WHERE x[4]
|
| Nice framing, and makes your wish quite understandable.
| A list comprehension can have one or more occurrences
| of 'for' and zero or more of 'if', but you might mostly
| frame those as joins:-).
A small article describing this analogy would have
helped me pick-up list comprehensions fairly quickly.
| temp = []
| for x in list:
| if x[4]:
| temp.append(process(x))
| return temp
|
| where would the new 'sortdesc' keyword fit in this model?
Let's consider...
[process(x) for x in mylist if x[4] sortdesc x[3] ]
So here is an extended "model"...
has_sortby = 1
is_desc = 1
temp = []
for x in mylist:
if x[4]:
val = process(x)
if has_sortby:
val = (x[3],val)
temp.append(val)
if not(has_sortby):
return temp
else:
temp.sort()
if is_desc: temp.reverse()
ret = []
for x in temp: ret.append(x[1])
return ret
Does this "fit" in as an extension of the model?
| map(process, sorted_by(2,
| [x for x in mylist if x[4]], descend=1))
It works... but it's a bit ugly. I'd like a
more "intuitive" syntax... and without having
to roll my own sort function. I would think
that sorting lists as part of a list comprehension
would be a common activity... I certainly do it
often enough.
| def sorted_by(col, alist, descend=0):
| temp = [(x[col],x) for x in alist]
| temp.sort()
| if descend: temp.reverse()
| return temp
Thanks... I'm going to use this solution; but
it'd be cool if list comprehensions were extended
a bit to allow for sorting... thank you so much
for your response Alex.
Best,
Clark
More information about the Python-list
mailing list