Python 当特定项出现时,如何将一个数组拆分为多个数组?

Python 当特定项出现时,如何将一个数组拆分为多个数组?,python,arrays,Python,Arrays,那么,当一个特定项出现时,有没有一种方法可以将一个数组拆分为多个数组?例如,每次spilt出现时,我都要切断并溢出数组。结果应该是: original = ["item", "anotherItem", "SPILT", "Item1", "item2"] array1 = ["item", "anotherItem"] array2 = ["It

那么,当一个特定项出现时,有没有一种方法可以将一个数组拆分为多个数组?例如,每次
spilt
出现时,我都要切断并溢出数组。结果应该是:

original = ["item", "anotherItem", "SPILT", "Item1", "item2"]
array1 = ["item", "anotherItem"]
array2 = ["Item1", "item2"]
此外,数组可以更改,因此
SPILT
的索引不确定

original = ["item", "anotherItem", "SPILT", "Item1", "item2"]

#Is the final array which contains all the split arrays
newarr = []
#Is a temporary array that stores the current chain of elements
currarr = []
for i in original:
    #if the splitting keyword is reached
    if i=="SPILT":
        #put all the current progress as a new array element, start afresh
        newarr.append(currarr)
        currarr = []
    else:
        #just add the element to the current progress
        currarr.append(i)
#add the final split segment of the array into the array of split segments
newarr.append(currarr)

print(newarr)

这些评论有必要的解释。直观的解决方案。

如果只出现一次
SPILT
,这应该可以:

array1 = original[:original.index('SPILT')]
array2 = original[original.index('SPILT')+1:]

如果拆分多次发生,那么这应该可以工作

original = ["item", "anotherItem", "SPLIT", "Item1", "item2", "SPLIT", "Item3", "item4"]
if 'SPLIT' in original:    
    test = '$'.join(original)
    splited_arrays = [data.split('$') for data in test.split('$SPLIT$')]

我认为“SPILT”会出现多次,但是是的,您的解决方案最适合于“SPILT”的单个实例。我留下了一个处理多次出现的解决方案。是的,它确实取决于原始数组。谢谢你的回答和详细解释!不客气:这是假设$不会以正确的方式出现在字符串中的任何位置,从而破坏您的方法。否则,这是一个很好的解决方案。谢谢你的回答@普罗米修斯:你可以用任何独特的东西来代替$,这不会引起任何问题。谢谢你的回答!
original = ["item", "anotherItem", "SPLIT", "Item1", "item2", "SPLIT", "Item3", "item4"]
if 'SPLIT' in original:    
    test = '$'.join(original)
    splited_arrays = [data.split('$') for data in test.split('$SPLIT$')]