Is there any equivalent to split 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]]
Use the array_split() method, pass in the array you want to split and the number of splits you want to do.
array_split() method in Python is used to split a 2D array into multiple sub-arrays of equal size.
Splitting the Array Into Even Chunks Using slice() Method The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.
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 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 wanted 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 could subclass list like so:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With