【问题标题】:Python string split combination [closed]Python字符串拆分组合[关闭]
【发布时间】:2015-11-16 14:07:37
【问题描述】:

我有一个像123[4-6][1-2] 这样的字符串,我想要一个函数,它可以为我提供所有组合的列表:

['12341', '12342', '12351', '12352', '12361', '12362']

输入字符串可以是[12-45]888[1-2]76[0-9] 之类的值,我希望 Python 中的函数能够为我提供包含所有组合的列表。

【问题讨论】:

  • @Woot4Moo ... 在这里发帖。
  • @Leb har har,我正在寻找一个代码 sn-p 尝试并未能正常工作。
  • 你应该可以用 12 行基本的 python 技能完成它,并且不需要外部导入

标签: python string combinations


【解决方案1】:

使用正则表达式查找范围并使用itertools.product 查找所有可能性。

import re
from itertools import product

def getranges(s):
    for a, b in re.findall(r"\[(\d+)-(\d+)\]", s):
        yield range(int(a), int(b)+1)

def strcombs(s):
    for r in product(*getranges(s)):
        it = iter(str(i) for i in r)
        yield re.sub(r"\[\d+-\d+\]", lambda _: next(it), s)

s = "123[4-6][1-2]"
print(list(strcombs(s)))    # ['12341', '12342', '12351', '12352', '12361', '12362']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多