Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pythonic way to rewrite an assignment in an if statement

Is there a pythonic preferred way to do this that I would do in C++:


for s in str:
    if r = regex.match(s):
        print r.groups()

I really like that syntax, imo it's a lot cleaner than having temporary variables everywhere. The only other way that's not overly complex is


for s in str:
    r = regex.match(s)
    if r:
        print r.groups()

I guess I'm complaining about a pretty pedantic issue. I just miss the former syntax.

like image 257
Falmarri Avatar asked Sep 19 '10 03:09

Falmarri


1 Answers

How about

for r in [regex.match(s) for s in str]:
    if r:
        print r.groups()

or a bit more functional

for r in filter(None, map(regex.match, str)):
    print r.groups()
like image 50
Ivo van der Wijk Avatar answered Oct 17 '22 02:10

Ivo van der Wijk