Using Python with Arrays

Is there any split equivalent for arrays?

a = [1, 3, 4, 6, 8, 5, 3, 4, 5, 8, 4, 3] separator = [3, 4] (len(separator) can be any) b = a.split(separator) b = [[1], [6, 8, 5], [5, 8, 4, 3]] 
+5
source share
4 answers

No, but we could write a function to do such a thing, and then, if you need it to be an instance method, you could subclass or encapsulate the list.

 def separate(array,separator): results = [] a = array[:] i = 0 while i<=len(a)-len(separator): if a[i:i+len(separator)]==separator: results.append(a[:i]) a = a[i+len(separator):] i = 0 else: i+=1 results.append(a) return results 

If you want this to work as an instance method, we could do the following to encapsulate the list:

 class SplitableList: def __init__(self,ar): self.ary = ar def split(self,sep): return separate(self.ary,sep) # delegate other method calls to self.ary here, for example def __len__(self): return len(self.ary) a = SplitableList([1,3,4,6,8,5,3,4,5,8,4,3]) b = a.split([3,4]) # returns desired result 

or we can make a list of subclasses as follows:

 class SplitableList(list): def split(self,sep): return separate(self,sep) a = SplitableList([1,3,4,6,8,5,3,4,5,8,4,3]) b = a.split([3,4]) # returns desired result 
+3
source

No no. You will have to write your own

or take this:

 def split(a, sep): pos = i = 0 while i < len(a): if a[i:i+len(sep)] == sep: yield a[pos:i] pos = i = i+len(sep) else: i += 1 yield a[pos:i] print list(split(a, sep=[3, 4])) 
+3
source

You can join the list to a string using a non-numeric separator, and then split:

 >>> s = " {} ".format(" ".join(map(str, a))) >>> s ' 1 3 4 6 8 5 3 4 5 8 4 3 ' >>> [[int(y) for y in x.split()] for x in s.split(" 3 4 ")] [[1], [6, 8, 5], [5, 8, 4, 3]] 

In two additional spaces in the line, boundary cases are taken into account (for example, a = [1, 3, 4] ).

0
source

For efficiency (50 x) on large arrays, there is an np.split method that you can use. the difficulty lies in removing the delimiter:

 from pylab import * a=randint(0,3,10) separator=arange(2) ind=arange(len(a)-len(separator)+1) # splitting indexes for i in range(len(separator)): ind=ind[a[ind]==separator[i]]+1 #select good candidates cut=dstack((ind-len(separator),ind)).flatten() # begin and end res=np.split(a,cut)[::2] # delete separators print(a,cut,res) 

gives:

 [0 1 2 0 1 1 2 0 1 1] [0 2 3 5 7 9] [[],[2],[1, 2],[1]] 
0
source

Source: https://habr.com/ru/post/1240384/


All Articles