List help to split into single entries - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: List help to split into single entries (/thread-22728.html) |
List help to split into single entries - paul41 - Nov-24-2019 I have a list which is in the following format: list = ['A -> B', 'C -> D', 'E -> F'] I am trying to find a way to produce a list of single entries in the following format: ['A','B','C','D','E','F'] When I incorrectly attempt to split by using; newList = [] for item in list: newList.append(item.split('->')) print(newList)This incorrectly produces: [['A','B], ['C','D'], ['E','F']] Any help and advice would be greatly appreciated. RE: List help to split into single entries - perfringo - Nov-24-2019 Never use list as a name. You overwrite built-in datatype list. You should use 'extend' instead of 'append': >>> lst = ['A -> B', 'C -> D', 'E -> F'] >>> new_list = [] >>> for item in lst: ... new_list.extend(item.split(' -> ')) ... >>> new_list ['A', 'B', 'C', 'D', 'E', 'F'] RE: List help to split into single entries - paul41 - Nov-24-2019 Thank you that was exactly what I was looking for and gives me the results I require. In my data set I seem to have some whitespace in some of the items. Do you know how i can remove this within the same for loop? RE: List help to split into single entries - perfringo - Nov-25-2019 (Nov-24-2019, 04:31 PM)paul41 Wrote: In my data set I seem to have some whitespace in some of the items. Do you know how i can remove this within the same for loop? If the whitespaces are around arrow then code above takes care of that (it breaks at ' -> '). If there are additional whitespaces (at the beginning or end) then they could be stripped: >>> lst = ['A -> B ', ' C -> D', ' E -> F '] # note spaces at start and end >>> new = [] >>> for item in lst: ... new.extend(chunk.strip() for chunk in item.split(' -> ')) ... >>> new ['A', 'B', 'C', 'D', 'E', 'F'] >>> [chunk.strip() for item in lst for chunk in item.split(' -> ')] # same result with list comprehension ['A', 'B', 'C', 'D', 'E', 'F'] |