2 回答
TA贡献1784条经验 获得超7个赞
假设您的数据没有任何退化情况,我们将始终期望 a'}','{'将您的组分开。
因此,获得所需输出的一种简单方法是将字符串连接在一起,拆分}然后格式化结果列表元素。
l = ['{','k0c','k1b','k2b','k3b','}','{','\\g0','\\g1','\\g2','\\g3','}']
out = [x.replace("{,", "{").strip(", ") + " }" for x in ", ".join(l).split("}") if x]
print(out)
['{ k0c, k1b, k2b, k3b }', '{ \\g0, \\g1, \\g2, \\g3 }']
TA贡献1111条经验 获得超0个赞
像这样的事情应该可以解决问题:
input_data = [
"{",
"k0c",
"k1b",
"k2b",
"k3b",
"}",
"{",
"\\g0",
"\\g1",
"\\g2",
"\\g3",
"}",
]
lists = []
current_list = None
for atom in input_data:
if atom == "{":
assert current_list is None, "nested lists not supported"
current_list = []
lists.append(current_list)
elif atom == "}":
current_list.append(atom)
current_list = None
continue
assert current_list is not None, (
"attempting to add item when no list active: %s" % atom
)
current_list.append(atom)
for lst in lists:
print(" ".join(lst))
输出是
{ k0c k1b k2b k3b }
{ \g0 \g1 \g2 \g3 }
但是你可以对字符串列表做任何你喜欢的事情。
添加回答
举报