那么,当一个特定的项目到来时,有没有办法把一个数组分成多个呢?例如,我想在每次SPILT到来时切断并溢出数组。结果应该是这样的:
original = ["item", "anotherItem", "SPILT", "Item1", "item2"]
array1 = ["item", "anotherItem"]
array2 = ["Item1", "item2"]此外,数组可能会更改,因此SPILT的索引不是确定的。
发布于 2021-05-19 17:09:48
如果SPILT只出现一次,这应该是可行的:
array1 = original[:original.index('SPILT')]
array2 = original[original.index('SPILT')+1:]发布于 2021-05-19 17:08:44
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)评论有必要的解释。直观的解决方案。
发布于 2021-05-19 17:24:46
divider = original.index("SPILT")
print(divider)
array1 = original[:divider]
array2 = original[divider+1:]
print(f"{array1}, \n{array2}")https://stackoverflow.com/questions/67600104
复制相似问题