2012-11-20 24 views
0

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

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

如何从原来的这种创建列表的新列表,它正确地显示

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

可能重复的[Python的解析CSV正确(http://stackoverflow.com/questions/12296585/python-parse-csv-correctly) –

+1

你能证明你的存在码? – Ren

+0

如果你想解析CSV数据,'csv'模块应该总是你看起来的第一个地方。只有当你无法用一种让模块快乐的方式描述你的格式的怪癖时,你应该费心编写你自己的解析器。 – abarnert

回答

2

假设你有名单这里叫做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']] 
>>>