Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python use split with arrays

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]]
like image 574
user1618465 Avatar asked Jan 11 '16 22:01

user1618465


People also ask

How do you split an array in Python?

Use the array_split() method, pass in the array you want to split and the number of splits you want to do.

How do you split a 2D array in Python?

array_split() method in Python is used to split a 2D array into multiple sub-arrays of equal size.

Can you split an array?

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.


1 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 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
like image 197
Matthew Avatar answered Sep 21 '22 23:09

Matthew