Example:
delimiter = "x"
input = ["x","a","x","x",1,2,3,"a","a","x","e"]
output = [["x","a"], ["x"], ["x",1,2,3,"a","a"], ["x","e"]]
Step 1: Find the indices where the variable
occurs in your list:
idx = [ix for ix, val in enumerate(input) if val==variable]
Step 2: Generate sub-lists using list slicing:
res = [input[i:j] for i,j in zip(idx, idx[1:]+[len(input)])]
Output
print(res)
# [['x', 'a'], ['x'], ['x', 1, 2, 3, 'a', 'a'], ['x', 'e']]
You can use the below function to get desired output.
Try this :
def splitList(inputList, delim):
finalList = []
chunk = []
for val in inputList:
if val == delim:
finalList.append(chunk)
chunk = [delim]
else:
chunk.append(val)
finalList.append(chunk)
return finalList[1:]
my_input_list = ["x","a","x","x",1,2,3,"a","a","x","e"]
my_output = splitList(my_input_list, "x") #just call the function with input_list and delimiter to split onto.
print(my_output)
>>> [["x","a"],["x"],["x",1,2,3,"a","a"],["x","e"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With