在Python中的某个值之间提取子数组

use*_*667 5 python arrays numpy list

我有一个值列表,这是合并许多文件的结果.我需要填充一些值.我知道每个子节以值-1开头.我试图通过迭代基本上在主数组中的-1之间提取一个子数组.

例如,假设这是主要列表:

-1 1 2 3 4 5 7 -1 4 4 4 5 6 7 7 8 -1 0 2 3 5 -1
Run Code Online (Sandbox Code Playgroud)

我想提取-1之间的值:

list_a = 1 2 3 4 5 7
list_b = 4 4 4 5 6 7 7 8
list_c = 0 2 3 5 ...
list_n = a1 a2 a3 ... aM
Run Code Online (Sandbox Code Playgroud)

我通过搜索主列表提取了每个-1的索引:

 minus_ones = [i for i, j in izip(count(), q) if j == -1]
Run Code Online (Sandbox Code Playgroud)

我还使用常用配方将它们组装成对:

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a,b)

for index in pairwise(minus_ones):
    print index
Run Code Online (Sandbox Code Playgroud)

我想要做的下一步是获取索引对之间的值,例如:

 list_b: (7 , 16) -> 4 4 4 5 6 7 7 8 
Run Code Online (Sandbox Code Playgroud)

所以我可以对这些值做一些工作(我将为每个子数组中的每个值添加一个固定的int.).

Joe*_*ton 4

numpy在标签中提到过。如果您正在使用它,请看一下np.split

例如:

import numpy as np

x = np.array([-1, 1, 2, 3, 4, 5, 7, -1, 4, 4, 4, 5, 6, 7, 7, 8, -1, 0, 2,
               3, 5, -1])
arrays = np.split(x, np.where(x == -1)[0])
arrays = [item[1:] for item in arrays if len(item) > 1]
Run Code Online (Sandbox Code Playgroud)

这产生:

[array([1, 2, 3, 4, 5, 7]),
 array([4, 4, 4, 5, 6, 7, 7, 8]),
 array([0, 2, 3, 5])]
Run Code Online (Sandbox Code Playgroud)

发生的事情是,这where将产生一个数组(实际上是一个数组元组,因此是where(blah)[0]),其中给定表达式为 true 的索引。然后我们可以传递这些索引来split获取数组序列。

-1但是,如果序列以 开头,结果将在开头包含和一个空数组-1。因此,我们需要将这些过滤掉。

不过,如果您尚未使用numpy,您的(或@DSM)itertools解决方案可能是更好的选择。