Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to split elements within a nested list by comma

Below is the list.

List=[['hello', 'how'], ['are', 'you', 'hope'], ['you,are,fine', 'thank', 'you']]

I want the output list as

List=[['hello', 'how'], ['are', 'you', 'hope'], ['you', 'are' ,'fine', 'thank', 'you']]
like image 395
Ann Mary Avatar asked Feb 17 '26 20:02

Ann Mary


2 Answers

Try the following nested comprehension that recompiles the list in a single walk-through while splitting the tokens:

>>> [[token for el in sub for token in el.split(',')] for sub in List]
[['hello', 'how'], ['are', 'you', 'hope'], ['you', 'are', 'fine', 'thank', 'you']]
like image 92
user2390182 Avatar answered Feb 20 '26 13:02

user2390182


Using a simple iteration and str.split

Ex:

lst=[['hello', 'how'], ['are', 'you', 'hope'], ['you,are,fine', 'thank', 'you']]
result = []
for i in lst:
    temp = []
    for j in i:
        temp += j.split(",")
    result.append(temp)
print(result)

Output:

[['hello', 'how'],
 ['are', 'you', 'hope'],
 ['you', 'are', 'fine', 'thank', 'you']]
like image 37
Rakesh Avatar answered Feb 20 '26 14:02

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!