基于分隔符连接列表中的字符串元素

2024-10-02 22:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一些分隔符的基础上组合列表中的所有元素;当分隔符对大于1时,我将面临困难。你知道吗

假设列表如下:

['{','k0c','k1b','k2b','k3b','}','{','\\g0','\\g1','\\g2','\\g3','}']

此列表中有12项

每当它找到{和}时,我希望将这些索引中的所有元素连接成一个元素,以便:

['{ k0c, k1b, k2b, k3b }' , '{\\g0 , \\g1, \\g2, \\g3 }' ]

此列表中的2项是我想要的,分隔符中的所有元素都变成了列表中的一个元素。你知道吗


Tags: 元素列表基础分隔符g1g2项是g0
2条回答

假设您的数据没有任何退化情况,我们总是希望'}','{'来分隔您的组。你知道吗

因此,获得所需输出的简单方法是将字符串连接在一起,在}上拆分,然后格式化生成的列表元素。你知道吗

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 }']

像这样的东西应该会起作用:

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 }

但是你可以用字符串列表做任何你喜欢的事情。你知道吗

相关问题 更多 >