[Python-ideas] More power in list comprehensions with the 'as' keyword
Cesare Di Mauro
cesare.dimauro at a-tono.com
Thu Aug 28 10:56:52 CEST 2008
A solution could be this:
[stripped for l in text.split('\n') with l.strip() as stripped if stripped != '']
so that you can keep both values (l and l.strip()) too.
Cheers,
Cesare
On 27 agu 2008 at 18:51:41, Tarek Ziadé <ziade.tarek at gmail.com> wrote:
> Hello
>
> There's a pattern I am doing all the time: filtering out some elements of a
> list, and cleaning them in the same move.
>
> For example, if I have a multi line text, where I want to:
>
> - keep non empty lines
> - clean non empty lines
>
> I am doing:
>
> >>> text = """
> ... this is a multi-line text\t
> ...
> ... \t\twith
> ...
> ... muliple lines."""
>
> >>> [l.strip() for l in text.split('\n') if l.strip() != '']
> ['this is a multi-line text', 'with', 'muliple lines.']
>
> It is not optimal, because I call strip() twice. I could use ifilter then
> imap or even use a real loop, but I
> want my simple, concise, list comprehension ! And I couldn't find a simple
> way to express it.
>
> The pattern can be generically resumed like this :
>
> [transform(e) for e in seq if some_test(transform(e))]
>
> So what about using the 'as' keyword to extend lists comprehensions, and
> to avoid calling transform() twice ?
>
> Could be:
>
> [transform(e) as transformed for e in seq if some_test(transformed)]
>
> In my use case I would simply have to write;:
>
> [l.strip() as stripped for l in text.split('\n') if stripped != '']
>
> Which seems to me clear and concise.
>
> Regards,
> Tarek
>
--
Dott. Cesare Di Mauro
A-Tono S.r.l.
T.: (+39)095-7365314
Information in this email is confidential and may be privileged. It is intended for the addresses only.
If you have received it in error, please notify the sender immediately and delete it from your system. You should not otherwise copy it, retransmit it or use or disclose its content to anyone.
Thank you for your co-operation.
More information about the Python-ideas
mailing list