【问题标题】:Python: re.sub single item in list with multiple itemsPython:re.sub 列表中的单个项目与多个项目
【发布时间】:2013-03-01 02:53:52
【问题描述】:

我是 Python 新手,尝试使用 re.sub 或其他方法在列表中查找单个项目并替换为多个项目。例如:

import re
list = ['abc', 'def']
tolist = []
for item in list:
    a = re.sub(r'^(.)(.)(.)$', '\\1\\2', '\\2\\3', item)
    tolist.append(a)
print tolist  # want: ['ab', 'bc', 'de', 'ef']

'\1\2', '\2\3' 部分显然不起作用,只是用来蹩脚地说明这个想法。

【问题讨论】:

  • list 是一个内置类型。不要将其用作变量名。
  • J.F.,列夫:感谢您了解这一点
  • 感谢大家的澄清和想法。在实践中,我正在处理可变长度项目的列表,即 ['abc', 'defg'],我需要将操作限制为 3 个字符的项目。

标签: regex list python-2.7


【解决方案1】:

这是一种相当通用的方法,其中您有一个元组列表,其中包含您想要对每个项目执行的所有替换:

In [1]: import re

In [2]: subs = [(r'^(.)(.)(.)$', r'\1\2'), (r'^(.)(.)(.)$', r'\2\3')]

In [3]: inlist = ['abc', 'def']

In [4]: [re.sub(*sub, string=s) for s in inlist for sub in subs]
Out[4]: ['ab', 'bc', 'de', 'ef']

每个元组中的第二个元素也可以是一个函数,因为re.sub 允许它。我重命名了您的初始列表,因为list 是一个内置类型名称,不应用于变量。

【讨论】:

    【解决方案2】:
    >>> res = []
    >>> m = re.compile('(..)')
    >>> for items in list:
    ...   for p in range(0,len(items)):
    ...     r = m.search(items[p:])
    ...     if r != None:
    ...        res.append(r.group())
    

    创建一个匹配两个字符并将它们分组的正则表达式

    第一个for循环,迭代列表

    第二个for循环,每个列表项中的字符索引

    搜索从偏移量开始的字符对

    存储任何找到的东西

    【讨论】:

      【解决方案3】:

      您可以在没有正则表达式的情况下配对字符:

      lst = ['abc', 'def']
      result = [a+b for chars in lst for a, b in zip(chars, chars[1:])]
      print(result)
      # -> ['ab', 'bc', 'de', 'ef']
      

      【讨论】:

        猜你喜欢
        • 2020-01-11
        • 1970-01-01
        • 1970-01-01
        • 2017-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-07
        • 1970-01-01
        相关资源
        最近更新 更多