给定切片列表,如何按顺序拆分序列?

lat*_*lip 11 python

给定切片列表,如何基于它们分离序列?

我有很长的氨基酸字符串,我想根据列表中的起止值进行拆分.一个例子可能是最明确的解释方式:

str = "MSEPAGDVRQNPCGSKAC"
split_points = [[1,3], [7,10], [12,13]]

output >> ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']
Run Code Online (Sandbox Code Playgroud)

额外的括号是显示从split_points列表中选择的元素.我不认为开始 - 停止点会重叠.

我有一堆可行的想法,但看起来非常低效(代码长度明智),似乎必须有一个很好的pythonic方式来做到这一点.

Joc*_*zel 9

你在那里分裂字符串的奇怪方法:

def splitter( s, points ):
    c = 0
    for x,y in points:
        yield s[c:x]
        yield "(%s)" % s[x:y+1]
        c=y+1
    yield s[c:]

print list(splitter(str, split_points))
# => ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']

# if some start and endpoints are the same remove empty strings.
print list(x for x in splitter(str, split_points) if x != '')
Run Code Online (Sandbox Code Playgroud)