pythonic way to rewrite an assignment in an if statement

前端 未结 7 838
隐瞒了意图╮
隐瞒了意图╮ 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:21

    There's a recipe to make an assignment expression but it's very hacky. Your first option doesn't compile so your second option is the way to go.

    ## {{{ http://code.activestate.com/recipes/202234/ (r2)
    import sys
    def set(**kw):
        assert len(kw)==1
    
        a = sys._getframe(1)
        a.f_locals.update(kw)
        return kw.values()[0]
    
    #
    # sample
    #
    
    A=range(10)
    
    while set(x=A.pop()):
        print x
    ## end of http://code.activestate.com/recipes/202234/ }}}
    

    As you can see, production code shouldn't touch this hack with a ten foot, double bagged stick.

提交回复
热议问题