+-

是否有任何等效的数组拆分?
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]]
最佳答案
不,但我们可以写一个函数来做这样的事情,然后如果你需要它作为一个实例方法,你可以子类化或封装列表.
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
如果您希望将其作为实例方法使用,我们可以执行以下操作来封装列表:
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或者我们可以像这样子类化列表:
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 点击查看更多相关文章
转载注明原文:Python使用split与数组 - 乐贴网