ycenycute
ycenycute

Reputation: 728

convert a list of lists to a list of string

I have a list of lists like this

list1 = [['I am a student'], ['I come from China'], ['I study computer science']]
len(list1) = 3

Now I would like to convert it into a list of string like this

list2 = ['I', 'am', 'a', 'student','I', 'come', 'from', 'China', 'I','study','computer','science']
len(list2) = 12

I am aware that I could conversion in this way

new_list = [','.join(x) for x in list1]

But it returns

['I,am,a,student','I,come,from,China','I,study,computer,science']
len(new_list) = 3

I also tried this

new_list = [''.join(x for x in list1)]

but it gives the following error

TypeError: sequence item 0: expected str instance, list found

How can I extract each word in the sublist of list1 and convert it into a list of string? I'm using python 3 in windows 7.

Upvotes: 0

Views: 2453

Answers (2)

jez
jez

Reputation: 15369

Following your edit, I think the most transparent approach is now the one that was adopted by another answer (an answer which has since been deleted, I think). I've added some whitespace to make it easier to understand what's going on:

list1 = [['I am a student'], ['I come from China'], ['I study computer science']]
list2 = [
    word
        for sublist in list1
        for sentence in sublist
        for word in sentence.split()
]
print(list2)

Prints:

['I', 'am', 'a', 'student', 'I', 'come', 'from', 'China', 'I', 'study', 'computer', 'science']

Upvotes: 1

bohrax
bohrax

Reputation: 1091

Given a list of lists where each sublist contain strings this could be solved using jez's strategy like:

list2 = ' '.join([' '.join(strings) for strings in list1]).split()

Where the list comprehension transforms list1 to a list of strings:

>>> [' '.join(strings) for strings in list1]
['I am a student', 'I come from China', 'I study computer science']

The join will then create a string from the strings and split will create a list split on spaces.

If the sublists only contain single strings, you could simplify the list comprehension:

list2 = ' '.join([l[0] for l in list1]).split()

Upvotes: 0

Related Questions