I have a list and I want to add the words that come after a certain word in this list into a new list.
exp input
list =["split","foo","foo","foo","split","mama","mama","split","orange","melon"]
exp output
list =["split","foo","foo","foo"]
["split","mama", "mama" ]
["split","orange","melon" ]
I encountered a logical error, I checked each child of the list and tried to throw the objects up to the next argument into a new list.
for i in liste:
if i.lower() == "split":
x = True
if x:
new_list.append(i)
I don’t know what to do after the first loop. How can I reset the bool value and create a new list?
>Solution :
You can simply iterate and keep a track of the current visisted set.
l =["split","foo","foo","foo","split","mama","mama","split","orange","melon"]
ans = []
curr = []
split_word = "split"
for i in l:
if i != split_word:
curr.append(i)
else:
if curr:
ans.append(curr)
curr = [i]
if curr:
ans.append(curr)
print(ans)
# [['split', 'foo', 'foo', 'foo'], ['split', 'mama', 'mama'], ['split', 'orange', 'melon']]