开发者

is there a way to make this code more terse?

Given a list of items, and a map from a predicate function to the "value" function, the code below applies "value" functions to the items satisfying the corresponding predicates:

my_re0 = re.compile(r'^([a-z]+)$')
my_re1 = re.compile(r'^([0-9]+)$')
my_map = [
    (my_re0.search, lambda x: x),
    (my_re1.search, lambda x: x),
    ]

for x in ['abc','123','a1']: for p, f in my_ma开发者_如何学Pythonp: v = p(x) if v: print f(v.groups()) break

Is there a way to express the same with a single statement?

If I did not have to pass the value returned by the predicate to the "value" function then I could do

for x in ['abc','123','a1']:
    print next((f(x) for p, f in my_map if p(x)), None)
Can something similar be done for the code above? I know, maybe it is better to leave these nested for loops, but I am just curious whether it is possible.


A bit less terse than Nate's ;-)

from itertools import product

comb = product(my_map, ['abc','123','a1'])
mapped = ((p(x),f) for (p,f),x in comb)
groups = (f(v.groups()) for v,f in mapped if v)
print next(groups), list(groups) # first match and the rest of them


[f(v.groups()) for x in ['abc','123','a1'] for p, f in my_map for v in [p(x)] if v]

You said more terse, right? ;^)


here is my version:

for x in ['abc','123','a1']:
    print next((f(v.groups()) for p, f in my_map for v in [p(x)] if v), None)
this version does not iterate over the whole my_map but stops as soon as the first successful mapping is found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜