I am trying to split my list into sublists based on the condition that anything within the element '|' would be considered as the elements for a new sublist. I am ignoring any elements with empty strings so those wont be included in the final list. I have the following list:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
The resulting result would then be:
[['a', 'b', 'c'], ['d', 'e']]
I have written the following code, can someone show me how to solve this please:
start = 0; end = 0
nlist = []
for s in range(0, len(slist)-1):
ns = s + 1
if slist[s] == '|' and ns == '|':
end = s - 1
elif slist[s] == '|':
start = s + 1
nlist.append(nlist[start:end])
>Solution :
The split/join technique advocated by @simre works for the data shown in the question. Here’s a loop-based approach that may be more flexible:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
result = []
e = []
for v in slist:
if v == '|':
if e:
result.append(e)
e = []
elif v:
e.append(v)
print(result)
Output:
[['a', 'b', 'c'], ['d', 'e']]
This also works where the strings in the list are comprised of more than one character. There is an implicit reliance on the last element in the list being equal to ‘|’.