pythonic way to rewrite an assignment in an if statement

前端 未结 7 835
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  旧时难觅i
    2020-12-19 11:08

    Perhaps it's a bit hacky, but using a function object's attributes to store the last result allows you to do something along these lines:

    def fn(regex, s):
        fn.match = regex.match(s) # save result
        return fn.match
    
    for s in strings:
        if fn(regex, s):
            print fn.match.groups()
    

    Or more generically:

    def cache(value):
        cache.value = value
        return value
    
    for s in strings:
        if cache(regex.match(s)):
            print cache.value.groups()
    

    Note that although the "value" saved can be a collection of a number of things, this approach is limited to holding only one such at a time, so more than one function may be required to handle situations where multiple values need to be saved simultaneously, such as in nested function calls, loops or other threads. So, in accordance with the DRY principle, rather than writing each one, a factory function can help:

    def Cache():
        def cache(value):
            cache.value = value
            return value
        return cache
    
    cache1 = Cache()
    for s in strings:
        if cache1(regex.match(s)):
            # use another at same time
            cache2 = Cache()
            if cache2(somethingelse) != cache1.value:
                process(cache2.value)
            print cache1.value.groups()
              ...
    

提交回复
热议问题