[英]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.