ipmev12 ipmev12 - 1 year ago 59
Python Question

breaking up a list entry in several lists at every /n Python 3

I am trying to create several lists by breaking up each list entry. the format is as follows:


['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\nNotes:replaced dsl cable and filter. Also rebooted all equipment. All working fine now.\nNext Action required:none\nAdded by jakubkwasny at 02/01/2014 21:41:40\nPinging 55:55:55:55 with 32 bytes of data:\nReply from 55:55:55:55: bytes=32 time=67ms TTL=240\nReply from 55:55:55:55: bytes=32 time=92ms TTL=240\nReply from 55:55:55:55: bytes=32 time=76ms TTL=240\nReply from 55:55:55:55: bytes=32 time=82ms TTL=240\nPing statistics for\nPackets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\nMinimum = 67ms, Maximum = 92ms, Average = 79ms']

basically, I have many entries in my list that follow this format and I need to break up each entry into several lists, starting a new list at each \n symbol. such as this:

list1 = root cause: hardware failure
list2 = action completed: power supply/filter/cable swap

and so on and this will need to do this for the thousands of entries so i have a list of all root causes a list of all actions completed and so and so on

I have managed to put /n symbol at each point I want a new list starting but not sure where to go from there

any help is appreciated

Answer Source

Use a list comp and str.splitlines to split every string in the lists into sublists of individual lines:

split_lines = [s.splitlines() for s in lst]

If you want each individual string inside a list:

  from itertools import chain

  split_lines = [[s] for s in chain(*map(str.splitlines, lst))]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download