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?
CodePudding user response:
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']]
CodePudding user response:
Instead of using a flag, you can append to the output list an empty sub-list when the input is 'split'
, and keep appending the current string to the last sub-list in the output:
lst =["split","foo","foo","foo","split","mama","mama","split","orange","melon"]
output = []
for s in lst:
if s == 'split':
output.append([])
output[-1].append(s)
print(output)
This outputs:
[['split', 'foo', 'foo', 'foo'], ['split', 'mama', 'mama'], ['split', 'orange', 'melon']]