a list/re problem

Lie Ryan lie.1296 at gmail.com
Sat Dec 12 11:22:19 EST 2009


On 12/12/2009 8:24 AM, Peter Otten wrote:
>>
>> But it is inefficient, because it is matching the regex twice for each
>> item, and it is a bit ugly.
>>
>> I could use:
>>
>>
>> n = []
>> for x in keys:
>>      m = r.match(x)
>>          if m:
>>              n.append(m.group(1))
>>
>>
>> It is more efficient, but much uglier.
>
> It's efficient and easy to understand; maybe you have to readjust your
> taste.

I agree, it's easy to understand, but it's also ugly because of the 
level of indentation (which is too deep for such a simple problem).

>> Does anyone have a better solution?

(sorry to ramble around)

A few months ago, I suggested an improvement in the python-ideas list to 
add a post-filter to list-comprehension, somewhere in this line:

a = [f(x) as F for x in l if c(F)]

where the evaluation of f(x) will be the value of F so F can be used in 
the if-expression as a post-filter (complementing list-comps' pre-filter).

Many doubted its usefulness since they say it's easy to wrap in another 
list-comp:
a = [y for y in (f(x) for x in l) if c(y)]
or with a map and filter
a = filter(None, map(f, l))

Up till now, I don't really like the alternatives.



More information about the Python-list mailing list