按某些重复索引值拆分列表

Mik*_*ssa 7 python indexing split element list

我有一个整数列表,其中一些是连续的数字.

是)我有的:

myIntList = [21,22,23,24,0,1,2,3,0,1,2,3,4,5,6,7] 等等...

我想要的是:

MyNewIntList = [[21,22,23,24],[0,1,2,3],[0,1,2,3,4,5,6,7]]
Run Code Online (Sandbox Code Playgroud)

我希望能够通过元素0拆分此列表,即,当循环时,如果元素为0,则将列表拆分为单独的列表.然后,在分割myIntList任意次数(基于找到元素0的重复)之后,我想将每个"分裂"或连续整数组附加到列表中的列表中.

我还可以使用'字符串列表'而不是整数来做同样的事情吗?(根据重复出现的元素将主字符串列表拆分为较小的列表)

编辑:

我如何按连续数字拆分列表?我的列表中有一部分从322跳到51,中间没有0.我想拆分:

[[...319,320,321,322,51,52,53...]]
Run Code Online (Sandbox Code Playgroud)

成

[[...319,320,321,322],[51,52,53...]]
Run Code Online (Sandbox Code Playgroud)

基本上,如何按连续数字拆分列表中的元素?

发布在此处: 按顺序拆分列表(整数)到单独的列表中

Pad*_*ham 5

it  = iter(myIntList)
out = [[next(it)]]
for ele in it:
    if ele != 0:
        out[-1].append(ele)
    else:
        out.append([ele])

print(out)
Run Code Online (Sandbox Code Playgroud)

或者在一个函数中:

def split_at(i, l):
    it = iter(l)
    out = [next(it)]
    for ele in it:
        if ele != i:
            out.append(ele)
        else:
            yield out
            out = [ele]
    yield out
Run Code Online (Sandbox Code Playgroud)

0如果你一开始就有 a ,它就会捕获:

In [89]: list(split_at(0, myIntList))
Out[89]: [[21, 22, 23, 24], [0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7]]

In [90]: myIntList = [0,21, 22, 23, 24, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7]

In [91]: list(split_at(0, myIntList))
Out[91]: [[0, 21, 22, 23, 24], [0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7]]
Run Code Online (Sandbox Code Playgroud)