Python3中如何在字符串[[1 -1 -1 -1][-1 2399 -1 -1]]中插入分隔符形成嵌套的列表
时间: 2024-09-15 09:14:10 浏览: 37
在Python 3中,你可以通过遍历原字符串,识别每个子列表的开始和结束,并在它们之间添加分隔符,如逗号或方括号`[]`,来形成嵌套的列表。这里是一个简单的例子:
```python
input_str = "[[1 -1 -1 -1][-1 2399 -1 -1]]"
separator = ", "
nested_list = []
# 遍历输入字符串,查找开始和结束符号
start = input_str.find("[")
end = start + 1
while end < len(input_str):
# 当找到子列表结束符号"]"时,将其转换为整数列表
sub_list = input_str[start:end].strip("[]").split()
nested_list.append([int(num) for num in sub_list])
# 更新开始位置查找下一个子列表
start = input_str.find("[", end)
if start == -1: # 如果找不到下一个开始位置,则认为遍历完成
break
else:
end = start + 1
print(nested_list)
```
运行上述代码后,你会得到一个嵌套的列表:
```
[[1, -1, -1, -1], [-1, 2399, -1, -1]]
```
阅读全文
相关推荐


















