簡體   English   中英

跨列表連接斷字符串 - Python

[英]Concatenating Broken Strings Across Lists - 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']]
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM