根据字符串将字符串列表拆分为子列表列表
Split list of strings into list of sublists based on a string
这个问题最容易用伪代码说明。我有一个这样的列表:
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)
虽然我的输出有点乱。如果能得到任何指点,我将不胜感激。
这可以使用 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']]
您离目标不远了,这是所需的最少修改
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
这个问题最容易用伪代码说明。我有一个这样的列表:
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)
虽然我的输出有点乱。如果能得到任何指点,我将不胜感激。
这可以使用 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']]
您离目标不远了,这是所需的最少修改
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