pythonic way to rewrite an assignment in an if statement

前端 未结 7 781
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 10:37

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 r

相关标签:
7条回答
  • 2020-12-19 11:31

    Whenever I find that my loop logic is getting complex I do what I would with any other bit of logic: I extract it to a function. In Python it is a lot easier than some other languages to do this cleanly.

    So extract the code that just generates the items of interest:

    def matching(strings, regex):
        for s in strings:
            r = regex.match(s)
            if r: yield r
    

    and then when you want to use it, the loop itself is as simple as they get:

    for r in matching(strings, regex):
        print r.groups()
    
    0 讨论(0)
提交回复
热议问题