【问题标题】:How can I keep the input data structure in a for loop?如何将输入数据结构保持在 for 循环中?
【发布时间】:2019-11-22 13:14:12
【问题描述】:

我有一个如下所示的元组列表:

l = [('xx-1711640.html', 'Hello'), 
     ('xx-8411747.html', 'Bye')
    ]

实际列表有数千个条目。现在我想对元组使用正则表达式。为此,我有一个 for 循环。此外,我希望输出也是一个元组列表。

我的代码:

ret = []
for line in l:
    for i in line:
        try:
            reg = re.sub(r'.+-', '', i)
            ret.append(reg)
        except:
            print(line)

但是,使用此代码,我的输出如下所示:

ret = ['1711640.html', 'Hello', '8411747.html', 'Bye']

当我希望它看起来像这样时:

ret = [('1711640.html', 'Hello'), ('8411747.html', 'Bye')]

我怎样才能正确地做到这一点?

【问题讨论】:

    标签: python regex python-3.x list tuples


    【解决方案1】:

    用途:

    ret = []
    for m,n in l:  #unpack tuple
        try:
            m = re.sub(r'.+-', '', m)   
            ret.append((m, n))
        except:
            print(m,n)
    

    输出:

    [('1711640.html', 'Hello'), ('8411747.html', 'Bye')]
    

    【讨论】:

      【解决方案2】:

      您可以在没有异常处理的情况下单行执行此操作:

      >>> [(re.sub(r'.+-', '', x), re.sub(r'.+-', '', y)) for x, y in l]
      [('1711640.html', 'Hello'), ('8411747.html', 'Bye')]
      

      【讨论】:

      • 我之前使用了一个列表理解,但是我不能在这个方法中包含 try 和 except。
      • 很公平,只是为了完整起见,我想把它包括在内!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多