【问题标题】:Assign and compare in python在python中分配和比较
【发布时间】:2015-01-04 19:41:17
【问题描述】:

我需要按顺序进行 re.match,在匹配的情况下,我需要匹配结果来选择组。现在我可以做下一步了:

r = re.match('cond1', l)
if r:
    # work with r.group()
else:
    r = re.match('cond2', l)
    if r:
        # work with r.group()
    else:
        r = re.match('cond3', l)
        if r:
            # work with r.group()

等等。但我怎样才能做得更好?我发现如果像这样就无法执行分配:

if r = re.match('cond1', l):
    # work with r.group()
elif r = re.match('cond2', l):
    # work with r.group()
elif r = re.match('cond3', l)
    # work with r.group()

【问题讨论】:

  • 不,这是不可能的。
  • 是的,我意识到了,但是如何更好地处理这样的问题?
  • 通常,当您尝试将 3 个或更多事物链接在一起时,最好询问如何将任意数量的事物链接在一起。这通常意味着循环(或隐式循环,例如,在对map 的调用中,或递归函数)。
  • 另外,如果你真的匹配这三种模式,为什么不直接匹配r = re.match('cond[123]', l)
  • 当您在六个月内返回此代码修复错误时,您的级联 if 很好(功能性、可理解、正常且易于理解.. ;-)

标签: python regex match


【解决方案1】:

你可以使用理解:

r, cond = next((m,c) for (m,c) in ((re.match(cond, line), cond) for cond in ('cond1', 'cond2', 'cond3')) if m)

if cond=='cond1':
    # work with r.group() for cond1
elif cond=='cond2':
    # work with r.group() for cond2

或者,如果这看起来太神秘,一个循环:

for cond in ('cond1', 'cond2', 'cond3'):
    r = re.match(cond, line)
    if r:
        break

if not r:
    # no match
elif cond=='cond1':
    # work with r.group() for cond1
elif cond=='cond2':
    # work with r.group() for cond2

【讨论】:

    【解决方案2】:

    首先,将事物重构为函数通常会有所帮助。在这种情况下,它会有所帮助,因为您可以轻松地从函数中提前返回;你不能从其他代码中间的代码块中提前返回。

    def first_match(haystack):
        r = re.match('cond1', haystack)
        if r:
            # work with r.group()
            return
        r = re.match('cond2', l)
        if r:
            # work with r.group()
            return
        r = re.match('cond3', l)
        if r:
            # work with r.group()
    

    所有else 位和缩进问题都消失了。


    此外,一般来说,当您询问如何将 3 个或更多事物链接在一起时,正确的答案是弄清楚如何将任意数量的事物链接在一起,并且只需使用 N=3 即可。这通常意味着一个循环(或隐藏在map 等函数内的循环,或递归函数定义等)。例如:

    def first_match(exprs, haystack):
        for expr in exprs:
            r = re.match(expr, haystack)
            if r:
                return r
    

    但是,在这种情况下,您尝试做的实际上是可行的。也许不是一个好主意,但是……正则表达式 match 对象总是真实的。当然None 是假的。所以:

    r = re.match('cond1', l) or re.match('cond2', l) or re.match('cond3', l)
    if r:
        # work with r.group(), which is the group for whichever matched
    

    但请注意,如果你想使用真实性,你也可以在循环中这样做:

    next(filter(bool, (re.match(cond, l) for cond in ('cond1', 'cond2', 'cond3'))))
    

    最后,你已经在使用正则表达式了,为什么不使用正则表达式呢?

    r = re.match('cond[123]', l)
    if r:
        # work with r.group()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2020-05-05
      • 1970-01-01
      • 2017-11-09
      • 2013-11-14
      • 2021-11-17
      相关资源
      最近更新 更多