跨列表连接断开的字符串 - python



我刚刚开始用Python编程。我已经将一些记录从文本文件读入列表,其中记录中的第四项是一个长字符串,有时跨越多行。例如

[ *, *, *, TXT1]
[TXT2]
[TXT3]
[ *, *, *, TXT4]
[TXT5]
[ *, *, *, TXT6]
[ *, *, *, TXT7]

如何从原始列表创建一个新的列表列表,使其正确显示

[ *, *, *, TXT1+TXT2+TXT3]
[ *, *, *, TXT4+TXT5]
[ *, *, *, TXT6]
[ *, *, *, TXT7]

假设这里有一个名为linelist的列表列表,看起来像[[*,*,*,TXT1],[TXT2],[TXT3],[*,*,*,TXT4],...]

newoutput = []
for item in linelist:
   if len(item) == 1:
       newoutput[-1][-1] += item[0]
   else:
       newoutput.append(item)

最后,您的输出将如下所示:

[
    [*,*,*,TXT1+TXT2+TXT3],
    ...
]

使用中:

>>> a
[['.', '.', '.', 'a'], ['b'], ['c'], ['.', '.', '.', 'd'], ['.', '.', '.', 'e']]
>>> newoutput = []
>>> for item in a:
...   if len(item) == 1:
...     newoutput[-1][-1] += item[0]
...   else:
...     newoutput.append(item)
...
>>> newoutput
[['.', '.', '.', 'abc'], ['.', '.', '.', 'd'], ['.', '.', '.', 'e']]
>>>

最新更新