如何根据输入列表中的模式(单词)制作带有子列表的列表?

时间:2015-07-13 18:24:16

标签: python list python-2.7 sublist

我有一个列表,其中由foo分隔的特定语句块如下:

a=['E3P.B99990001.pdb_138:6.923:0.241:6.116',  'E3P.B99990001.pdb_397:15.856:3.506:8.144', 'foo',

'E3P.B99990002.pdb_138:4.499:4.286:8.260', 'E3P.B99990002.pdb_397:14.897:3.238:9.338',  'foo']

在这里,我想为每个博客创建一个包含子列表的主列表,这些博客由模式“foo”分隔如下。

Mainlist=[
            ['E3P.B99990001.pdb_138:6.923:0.241:6.116',
             'E3P.B99990001.pdb_397:15.856:3.506:8.144']#sublist1 (read input list values until first "foo" and make first sublist)

            ['E3P.B99990002.pdb_138:6.923:0.241:6.116',
             'E3P.B99990002.pdb_397:15.856:3.506:8.144']#sublist2 (read input list values until first "foo" to second "foo" and make second sublist)

主要想法是使用“foo”作为分隔符来制作不同的子列表                                                                           ]

我希望它可以理解。如果有人知道你能帮助我吗?

提前感谢你

基于#Brien的代码给出了确切答案:

sub = []
for item in a:
    if item == 'foo':
        ATOM_COORDINATE.append(a)
        sub = []
    else:
        a.append(item)
print sub

输出:

[
['E3P.B99990001.pdb_138:6.923:0.241:6.116', 'E3P.B99990001.pdb_397:15.856:3.506:8.144', 'E3P.B99990001.pdb_424:8.558:1.315:6.627', 'E3P.B99990001.pdb_774:14.204:-5.490:24.812', 'E3P.B99990001.pdb_865:15.545:4.258:10.007', 'E3P.B99990001.pdb_929:16.146:-6.081:24.770'],
['E3P.B99990002.pdb_138:4.499:4.286:8.260', 'E3P.B99990002.pdb_397:14.897:3.238:9.338', 'E3P.B99990002.pdb_424:5.649:5.914:8.639', 'E3P.B99990002.pdb_774:12.114:-6.864:23.897', 'E3P.B99990002.pdb_865:15.200:3.910:11.227', 'E3P.B99990002.pdb_929:13.649:-6.894:22.589']
                                               ]

1 个答案:

答案 0 :(得分:1)

# assuming your original list is called biglist
Mainlist = []
sublist = []
for item in biglist:
    if item == 'foo':
        Mainlist.append(sublist)
        sublist = []
    else:
        sublist.append(item)