Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split items in list

Tags:

python

list

split

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 ], [] )
like image 574
Django Doctor Avatar asked Oct 09 '12 21:10

Django Doctor


People also ask

How do you split values in a list?

To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.

How do you separate items in a list Python?

Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Can we use split function in list?

Splitting the String Into a List: The given string or line can be split into a list using the split() function with any delimiters.


1 Answers

result = [item for word in words for item in word.split(',')]
like image 127
jfs Avatar answered Oct 03 '22 14:10

jfs