-1

Hi I have a list of elements which some elements have a ',' in between that I wish to split into seperate elements Ex:

['Agrigento',
 ' Tal Andar, Regie Curie',
 ' Landar ta il Geuenie',
 ' Landar ta il Guedi,  Casali Bisibud',
 'Aragonia',
 'Athene']

should look like:

 ['Agrigento',
     ' Tal Andar',
     ' Regie Curie',
     ' Landar ta il Geuenie',
     ' Landar ta il Guedi',  
     ' Casali Bisibud',
     'Aragonia',
     'Athene']

Any idea how it is possible. I want to keep both elements of the split

gannina
  • 173
  • 1
  • 8
  • Did you intentionally keep the single leading space, but collapse the double leading space to a single one? – tobias_k Aug 10 '18 at 09:07

2 Answers2

3

You can use a list-comprehension with the standard scheme for flattening arrays:

lst = ['Agrigento',
 ' Tal Andar, Regie Curie',
 ' Landar ta il Geuenie',
 ' Landar ta il Guedi,  Casali Bisibud',
 'Aragonia',
 'Athene']

lst = [x for y in lst for x in y.split(',')]
print(lst)  # -> ['Agrigento', ' Tal Andar', ' Regie Curie', ' Landar ta il Geuenie', ' Landar ta il Guedi', '  Casali Bisibud', 'Aragonia', 'Athene']

Note: We are taking advantage of the fact that splitting a string that does not contain the character used as a delimiter returns the same string in a list:

>> 'a'.split('b')
['a']

As a result, the flattening meets no obstacles. For more info, see split.


Finally, as @tobias says, if you want to get rid of the spaces in the front and back of the names, you can use the strip() method. Simply modify the above comprehension to the one given below.

lst = [x.strip() for y in lst for x in y.split(',')]
print(lst)  # -> ['Agrigento', 'Tal Andar', 'Regie Curie', 'Landar ta il Geuenie', 'Landar ta il Guedi', 'Casali Bisibud', 'Aragonia', 'Athene']
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • 1
    Might add a not about `x.strip()` as well, although OP is a bit inconsistent on whether to remove the spaces or not. – tobias_k Aug 10 '18 at 09:09
0
elements = ['Agrigento', ' Tal Andar, Regie Curie', ' Landar ta il Geuenie', ' Landar ta il Guedi,  Casali Bisibud', 'Aragonia', 'Athene']
result = []

for elem in elements:
    if ',' in elem:
        result.extend([s for s in element.split(',')])
    else:
        result.append(elem)

print(result)
Wenhan Wu
  • 96
  • 2