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 string within a list into a list of lists and further splitting its elements if special character found

I’ve got a list of strings that I split into a list of list on (‘/>’), yet I want to split the elements of that list within further depending on IF it has a certain character (‘/’) in it while maintaining the order that the ‘further elements’ are split in. So for example

lol=['FruitSalad://Fruits/Seasonal/Summer/>June>July>August>Mangoes/Grapes/Guava',
 'FruitSalad://Fruits/Seasonal/Winter/>Nov>Dec>Jan>Banana/Oranges',
 'FruitSalad://Fruits/Seasonal/Summer/>June>July>August>Pineapple']

 l1=[lol[_].split('/>')[-1].split('>') for _ in range(len(lol)) if '/>' in lol[_]]
>>> l1
[['June', 'July', 'August', 'Mangoes/Grapes/Guava'], ['Nov', 'Dec', 'Jan', 'Banana/Oranges'], ['June', 'July', 'August', 'Pineapple']]

Instead of the above, I’m trying to get

[['June', 'July', 'August', 'Mangoes', 'Grapes', 'Guava'], ['Nov', 'Dec', 'Jan', 'Banana', 'Oranges'], ['June', 'July', 'August', 'Pineapple']]

Any help is greatly appreciated! Please let me know if my question doesn’t make sense.
Not sure if this matters but this should work on python 2.7 and 3.6. Thank You!

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

>Solution :

  1. for each element, split on />
  2. Take the final element and replace the slash with > and then split again
 [l.split("/>",1)[-1].replace("/", ">").split(">") for l in lol]
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