用括号、子括号和空格分割字符串

问题描述 投票:0回答:1

在Python中,我有以下字符串:

string_example = '11 31 (31 573) ((11 573)<(31 573 [1 0 0])<(11 31))'

我想通过使用空格和“()”作为分隔符拆分字符串来提取列表,而不拆分子括号。所需的列表是:

list_split=['11', '31', '(31 573)', '((11 573)<(31 573 [1 0 0])<(11 31))']

python split space parentheses
1个回答
0
投票

思路:根据空格或括号分割字符串,如果有多个括号,则匹配相同数量的右括号结束分割。

def custom_split(string):
result = []
current = ""
count = 0
for char in string:
    if char == ' ' and count == 0:
        if current:
            result.append(current)
        current = ""
    elif char == '(':
        count += 1
        current += char
    elif char == ')' and count > 0:
        count -= 1
        current += char
        if count == 0:
            result.append(current)
            current = ""
    else:
        current += char

if current:
    result.append(current)

return result

string_example = '11 31 (31 573) ((11 573)<(31 573 [1 0 0])<(11 31))'
list_split = custom_split(string_example)
print(list_split)

此函数逐个字符地迭代输入字符串,并根据空格或括号进行分割。当遇到左括号时,计数器增加,当遇到右括号时,计数器减少。仅当计数器达到零时,当前拆分单元才会结束并添加到结果列表中。

© www.soinside.com 2019 - 2024. All rights reserved.