繁体   English   中英

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

[英]Extract subarray between certain value in Python

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

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

-1 1 2 3 4 5 7 -1 4 4 4 5 6 7 7 8 -1 0 2 3 5 -1

我想提取-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

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

 minus_ones = [i for i, j in izip(count(), q) if j == -1]

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

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

for index in pairwise(minus_ones):
    print index

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

 list_b: (7 , 16) -> 4 4 4 5 6 7 7 8 

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

你在标签中提到了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]

这会产生:

[array([1, 2, 3, 4, 5, 7]),
 array([4, 4, 4, 5, 6, 7, 7, 8]),
 array([0, 2, 3, 5])]

发生的事情是, where会产生一个数组(实际上是一个数组的元组,因此where(blah)[0] )指定表达式为真的指标。 然后我们可以通过这些指标进行split以获得一系列数组。

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

但是,如果您还没有使用numpy ,那么您的(或@ DSM) itertools解决方案可能是更好的选择。

如果你只需要这些组本身并且不关心组的索引(你总是可以重建它们),我会使用itertools.groupby

>>> from itertools import groupby
>>> seq = [-1, 1, 2, 3, 4, 5, 7, -1, 4, 4, 4, 5, 6, 7, 7, 8, -1, 0, 2, 3, 5, -1]
>>> groups = [list(g) for k,g in groupby(seq, lambda x: x != -1) if k]
>>> groups
[[1, 2, 3, 4, 5, 7], [4, 4, 4, 5, 6, 7, 7, 8], [0, 2, 3, 5]]

我错过了numpy标签:如果你正在使用numpy数组,使用np.split / np.where是一个更好的选择。

我会做这样的事情,这与你开始的路径有点不同:

input_list = [-1,1,2,3,4,5,7,-1,4,4,4,5,6,7,7,8,-1,0,2,3,5,-1]

list_index = -1
new_lists = []
for i in input_list:
    if i == -1:
        list_index += 1
        new_lists.append([])
        continue
    else:
        print list_index
        print new_lists
        new_lists[list_index].append(i)

我认为在构建list ,可以直接将值添加到string 因此,不是从像xx = []这样的list开始,而是从xx = '' ,然后执行类似xx = xx + ' ' + str (val) 结果将是string而不是list 然后,您可以在strihg上使用split()方法。

In [48]: xx
Out[48]: '-1 1 2 3 4 5 7 -1 4 4 4 5 6 7 7 8 -1 0 2 3 5 -1'

In [49]: xx.split('-1')
Out[49]: ['', ' 1 2 3 4 5 7 ', ' 4 4 4 5 6 7 7 8 ', ' 0 2 3 5 ', '']

In [50]: xx.split('-1')[1:-1]
Out[50]: [' 1 2 3 4 5 7 ', ' 4 4 4 5 6 7 7 8 ', ' 0 2 3 5 ']

我相信你可以从这里拿走它......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM