如何解析含特殊字符的变长尖括号包裹值列表?
提取含嵌套特殊字符的列表值
问题分析
你的列表项被<>包裹,且内部可能包含<、>和逗号,普通的字符串分割会误把内部逗号当成列表分隔符,必须通过跟踪嵌套层级来正确识别每个项的边界。
解决方案:栈驱动的字符遍历
用栈来记录<>的嵌套深度,只有当深度为0时,遇到的逗号才是列表项的分隔符。具体步骤:
- 移除字符串首尾的
[和],聚焦内部内容 - 遍历每个字符,用栈跟踪
<>的嵌套:- 遇到
<则入栈,深度+1 - 遇到
>则出栈,深度-1 - 遇到逗号且栈为空时,将当前累积的字符作为一个列表项,重置累积器
- 遇到
- 遍历结束后,处理最后一个未分割的项
- 对每个项,去掉最外层的
<>(因为原列表的每个值都被<>包裹)
Python 实现代码
def extract_nested_values(input_str): # 移除首尾的方括号 inner_content = input_str.strip('[]') stack = [] current_item = [] result = [] for char in inner_content: if char == '<': stack.append(char) current_item.append(char) elif char == '>': stack.pop() current_item.append(char) elif char == ',' and not stack: # 仅当无未闭合的<时,才分割项 cleaned_item = ''.join(current_item).strip() # 移除最外层的<> if cleaned_item.startswith('<') and cleaned_item.endswith('>'): cleaned_item = cleaned_item[1:-1] result.append(cleaned_item) current_item = [] else: current_item.append(char) # 处理最后一个项 if current_item: cleaned_item = ''.join(current_item).strip() if cleaned_item.startswith('<') and cleaned_item.endswith('>'): cleaned_item = cleaned_item[1:-1] result.append(cleaned_item) return result # 测试示例 test_case = '[<<a,b>>, <c: d/<e>>]' print(extract_nested_values(test_case)) # 输出: ['<a,b>', 'c: d/<e>']
边界情况适配
- 支持多层嵌套:比如输入
[<<<x,y>>> , <a,<b,c>>],会提取出<<x,y>>和a,<b,c> - 自动忽略项之间的空格:处理列表项前后的空格(比如
, <c:...>里的空格) - 兼容空项(如果你的列表允许的话)
内容的提问来源于stack exchange,提问作者Austin Mordahl
相关产品推荐
相关产品推荐

