首页 > 解决方案 > 这个python字符串怎么分解

问题描述

我需要按照以下示例中所示的格式将 python 字符串分解为字符串列表。

例子

有一个 python 字符串看起来像:

[1] 输入:

'they <are,are not> sleeping'

它必须变成一个列表,看起来像:

[1] 输出:

['they are sleeping', 'they are not sleeping'] 

另一个例子

[2] 输入:

'hello <stupid,smart> <people,persons,animals>'

[2] 输出:

['hello stupid people', 'hello stupid persons', 'hello stupid animals', 'hello smart people', 'hello smart persons', 'hello smart animals'] 

替代选项存在于标签中,并且需要考虑所有可能性来生成新字符串。

标签: pythonpython-3.x

解决方案


试试这个:

import itertools

def all_choices(text):
    """
    >>> list(all_choices('they <are,are not> sleeping'))
    ['they are sleeping', 'they are not sleeping']
    >>> list(all_choices('hello <stupid,smart> <people,persons,animals>'))
    ['hello stupid people', 'hello stupid persons', 'hello stupid animals', 'hello smart people', 'hello smart persons', 'hello smart animals']
    """
    tokens = (block2 for block1 in text.split('<')
                     for block2 in block1.split('>'))

    decisions = []
    literals = []

    try:
        while True:
            literal = next(tokens)
            literals.append(literal)
            options = next(tokens).split(',')
            decisions.append(options)
    except StopIteration:
        pass

    decisions.append(('',))

    for choices in itertools.product(*decisions):
        yield ''.join(x for pair in zip(literals, choices)
                        for x in pair)


推荐阅读