将字符串列表拆分为基于字符串的子列表

时间:2015-01-20 16:25:35

标签: python string list

这个问题在伪代码中最容易说明。我有一个这样的清单:

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)

虽然我的输出有些混乱。对于我能得到的任何指示,我将不胜感激。

2 个答案:

答案 0 :(得分:8)

使用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']]

答案 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