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 ], [] )
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.
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.
Splitting the String Into a List: The given string or line can be split into a list using the split() function with any delimiters.
result = [item for word in words for item in word.split(',')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With