0

In python 3, I have a list where each element of this list is a sentence string, for example

list = ["the dog ate a bone", "the cat is fat"] 

How do I split each sentence string into an individual list while keeping everything in the individual list, making it a 2 dimensional list

For example...

list_2 = [["the", "dog", "ate", "a", "bone"], ["the", "cat", "is", "cat"]]
trincot
  • 317,000
  • 35
  • 244
  • 286

2 Answers2

2

You can use list comprehension:

list2 = [s.split(' ') for s in list]
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    simple and elegant.i am new to python too .interesting how 10 lines can be reduced to only one line of code – AL-zami Sep 11 '16 at 18:05
0

You can simply do the following.Use split() method on each of the value and reassign the value of every index with new comma seperated text

mylist=['the dog ate a bone', 'the cat is fat']
print(mylist)

def make_two_dimensional(list):

    counter=0
    for value in list:
        list[counter]= value.split(' ')
        counter += 1

make_two_dimensional(mylist)
print(mylist)
AL-zami
  • 8,902
  • 15
  • 71
  • 130