Rich Tier
Rich Tier

Reputation: 9441

split items in list

How can I turn the following list

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

into

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

in the most pythonic way?

I have very unpythonic code that creates nested list, and then flatterens:

sum ( [ word.split(',') for word in words ], [] )

Upvotes: 7

Views: 3862

Answers (3)

raton
raton

Reputation: 428

      k=k=['1','2','A,B,C,D','7','8']
      m=[i for v in k for i in v if i!=","]

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

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 the 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']

Upvotes: 3

jfs
jfs

Reputation: 414079

result = [item for word in words for item in word.split(',')]

Upvotes: 19

Related Questions