Jam*_*mes 5 python string list
这个问题最容易在伪代码中说明.我有一个这样的列表:
linelist = ["a", "b", "", "c", "d", "e", "", "a"]
Run Code Online (Sandbox Code Playgroud)
我想以这种格式得到它:
questionchunks = [["a", "b"], ["c", "d", "e"], ["a"]]
Run Code Online (Sandbox Code Playgroud)
我的第一次尝试是这样的:
questionchunks = []
qlist = []
for line in linelist:
if (line != "" and len(qlist) != 0 ):
questionchunks.append(qlist)
qlist = []
else:
qlist.append(line)
Run Code Online (Sandbox Code Playgroud)
我的输出有点乱了.对于我能得到的任何指示,我将不胜感激.
您几乎接近目标,这是所需的最小编辑
linelist = ["a", "b", "", "c", "d", "e", "", "a"]
questionchunks = []
qlist = []
linelist.append('') # append an empty str at the end to avoid the other condn
for line in linelist:
if (line != "" ):
questionchunks.append(line) # add the element to each of your chunk
else:
qlist.append(questionchunks) # append chunk
questionchunks = [] # reset chunk
print qlist
Run Code Online (Sandbox Code Playgroud)
这可以通过以下方式轻松完成itertools.groupby
:
>>> from itertools import groupby
>>> linelist = ["a", "b", "", "c", "d", "e", "", "a"]
>>> split_at = ""
>>> [list(g) for k, g in groupby(linelist, lambda x: x != split_at) if k]
[['a', 'b'], ['c', 'd', 'e'], ['a']]
Run Code Online (Sandbox Code Playgroud)