[英]How can I spilt an array into multiple arrays when a specific item comes?
那么有沒有辦法在特定項目出現時將數組溢出到多個? 例如,我想在每次SPILT
到來時切斷並溢出陣列。 結果應該是這樣的:
original = ["item", "anotherItem", "SPILT", "Item1", "item2"]
array1 = ["item", "anotherItem"]
array2 = ["Item1", "item2"]
數組也可以改變,所以SPILT
的索引是不確定的。
如果SPILT
只出現一次,這應該有效:
array1 = original[:original.index('SPILT')]
array2 = original[original.index('SPILT')+1:]
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)
評論有必要的解釋。 直觀的解決方案。
divider = original.index("SPILT")
print(divider)
array1 = original[:divider]
array2 = original[divider+1:]
print(f"{array1}, \n{array2}")
如果 SPLIT 發生多次,那么這應該有效。
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$')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.