Python使用split函数与数组配合使用

6
有没有类似于数组分割的等效函数?
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]]

1
你有没有研究过itertools.groupby - TigerhawkT3
2
@TigerhawkT3 这会如何有所帮助? - Stefan Pochmann
这是一个不错的起点,如果没有其他的话。 - TigerhawkT3
2
@TigerhawkT3 我不认为在这里使用它有什么好的方法... - Stefan Pochmann
@TigerhawkT3 你认为我们应该按三和四分割,而不是按照序列[3,4]吗? - Stefan Pochmann
显示剩余2条评论
4个回答

4
不过,我们可以编写一个函数来实现这样的功能,如果您需要它成为一个实例方法,您可以继承或封装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

如果您想将此方法作为实例方法使用,可以通过以下方式封装列表:

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

我认为对于 [1, 3, 4] 它不起作用,它将返回 [[1]] 而不是 [[1], []]。 - Yoav Glazner
你是对的,我不确定是否应该出现空列表(如果希望行为像字符串分割运算符,则应该出现)。我已经编辑了代码来解决这个问题。 - Matthew

3

没有现成的解决方案,你需要自己编写代码。

或者你可以使用这个:

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]))

0
你可以使用非数字分隔符将列表连接成字符串,然后进行拆分:
>>> 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]]

字符串中的2个额外空格考虑到了边缘情况(例如:a = [1, 3, 4])。

0
为了在大数组上提高效率(50倍),可以使用np.split方法。难点在于删除分隔符“:”。
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)

给出:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接