这个问题在伪代码中最容易说明。我有一个这样的清单:
linelist = ["a", "b", "", "c", "d", "e", "", "a"]
我想以格式获取它:
questionchunks = [["a", "b"], ["c", "d", "e"], ["a"]]
我的第一次尝试就是:
questionchunks = []
qlist = []
for line in linelist:
if (line != "" and len(qlist) != 0 ):
questionchunks.append(qlist)
qlist = []
else:
qlist.append(line)
虽然我的输出有些混乱。对于我能得到的任何指示,我将不胜感激。
答案 0 :(得分:8)
>>> 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']]
答案 1 :(得分:8)
你几乎接近目标,这是所需的最小编辑
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