列表串联,将以“:”结尾的元素添加到列表,其他元素添加到子列表 - python

我需要格式化列表的输出格式,以使所有以:结尾的元素作为第一个元素,而其余元素位于该列表的子列表中。
例如:

假设我们有:

A: B, C
B: D, F | G

到目前为止,我所做的一切已将其转换为以下列表:

['A:', 'B,', 'C', 'B:', 'D,', ['F', 'G']]

但是现在我不知道如何到达以下输出:

[['A:',['B', 'C']], ['B:', ['D', ['F', 'G']]]

你能帮助我吗?

编辑:
这是我阅读的文件:

file = open('data.txt', 'r')
Y = []
for line in file:
    for word in line.strip().split():
        Y.append(str(word))

这部分是我将ors放在子列表中的位置:

text = []
i = 0
while True:
    if i > len(Y)-2:
        # No more possible |'s, so wrap things up
        text.append( Y[-1] )
        break
    if Y[i+1] == '|':
        # Add the items around the |; move past the group:
        if Y[i+2].endswith(','):
            Y[i+2] = Y[i+2].replace(",", "")
            text.append([Y[i], Y[i+2]])
        else:
            text.append([Y[i], Y[i+2]])
        i += 3
    else:
        # Add the current element & move on
        text.append( Y[i] )
        i += 1
for id in range(len(text)-1):
    if type(text[id]) != str:
        if text[id][-1] == text[id+1]:
            text.remove(text[id+1])

python大神给出的解决方案

为什么先拆分单词并将其放在列表中?您可以直接循环一行,并使用一个嵌套列表推导拆分它们:

import re
with open('data.txt', 'r') as f :
     [[k,[p,n.split('|')]] if '|' in n else [k,[p,n]] for k,(p,n) in [[i,j.split(',')] for i,j in [re.split(r'(?<=:) ',line) for line in f]]]

结果:

[['A:', ['B',' C']], ['B:', ['D', [' F ', ' G']]]]

但是请注意,这不是一般的解决方案!作为更通用的方法,如果可能有一些其他定界符而不是|,例如,如果它是一个无字字符,则可以使用正则表达式(n)拆分re.split(r'\W',n)变量。

注意:r'(?<=:) '是positive look behind,它将根据:后面的空格分割行。

如果不想用regex分隔行,可以使用str.partition:

with open('data.txt', 'r') as f :
    [[k,[p,n.split('|')]] if '|' in n else [k,[p,n]] for k,(p,n) in [[i+j,t.split(',')] for i,j,t in [line.partition(':') for line in f]]]
[['A:', [' B',' C']], ['B:', [' D', [' F ', ' G']]]]