Separate items in a list

How to include the following list

['1','2','A,B,C,D','7','8'] 

in

['1','2','A','B','C','D','7','8']

in the most pythonic way?

I have a very fearless code that creates a nested list, and then the latter:

 sum ( [ word.split(',') for word in words ], [] ) 
+7
source share
3 answers
 result = [item for word in words for item in word.split(',')] 
+19
source
 In [1]: from itertools import chain In [2]: lis=['1','2','A,B,C,D','7','8'] In [5]: list(chain(*(x.split(',') for x in lis))) Out[5]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8'] 

to further reduce unwanted split() calls:

 In [7]: list(chain(*(x.split(',') if ',' in x else x for x in lis))) Out[7]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8'] 

using map() :

 In [8]: list(chain(*map(lambda x:x.split(','),lis))) Out[8]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8'] In [9]: list(chain(*map(lambda x:x.split(',') if ',' in x else x,lis))) Out[9]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8'] 
+3
source
  k=k=['1','2','A,B,C,D','7','8'] m=[i for v in k for i in v if i!=","] 
0
source

All Articles