Home > Enterprise >  Splitting strings without resulting in 2-D list
Splitting strings without resulting in 2-D list

Time:06-06

How do I split strings in a list without resulting in a 2-D list?

list1:['Ben&Jerry', 'Julia', 'Sally&Don', 'Tom', 'Tracy&Jim']

to output:

['Ben','Jerry','Julia','Sally', 'Don','Tom','Tracy','Jim']

using

flat_list=[s.split('&') if "&" in s else s for s in list1 ]

will give me a 2-D list.

CodePudding user response:

Lazy way:

flat_list = '&'.join(list1).split('&')

CodePudding user response:

This should work

[i for j in [i.split('&') for i in list1] for i in j]
  • Related