Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splitting a list based on specific element

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ‘|’.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading