Python将拆分与数组一起使用

Python将拆分与数组一起使用,python,arrays,split,Python,Arrays,Split,对于阵列是否有任何等效的拆分 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]] 您可以使用非数字分隔符将列表连接到字符串,然后执行拆分: >>> s = " {} ".format(" ".join(map(str, a)))

对于阵列是否有任何等效的拆分

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

您可以使用非数字分隔符将列表连接到字符串,然后执行拆分:

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

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

否,但我们可以编写一个函数来完成这一任务,如果需要将其作为实例方法,则可以对列表进行子类化或封装

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(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

不,没有。你必须自己写

或者拿这个来说:

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]))
def拆分(a、sep):
pos=i=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]]

不,没有;这有什么意义?你甚至没有在你发明的调用中使用
分隔符
。它必须是一个列表列表,还是你只是想对与分隔符匹配的子数组进行排序?你研究过了吗?@TigerhawkT3这有什么帮助?@TigerhawkT3我看不到一个好的方法在这里使用它…我认为它对[1,3,4]不起作用,它会返回[[1]]而不是[[1],]]你是对的,我不确定这个空列表是否应该出现(如果希望表现得像字符串拆分操作符,应该出现)。我已经编辑了代码来解决这个问题。
[0 1 2 0 1 1 2 0 1 1] [0 2 3 5 7 9] [[],[2],[1, 2],[1]]