Home > other >  how to split list of sentences into another list(2D)?
how to split list of sentences into another list(2D)?

Time:06-13

I have a list named lists.

lists = [['Was the indus valley part of the maharashtra empire?',
  'Is there such a thing as golden age of indian culture?',
  'Is the vedic period the same as the golden age?']]

I want to convert all this sentences into different lists as shown below.

new_list = [['Was the indus valley part of the maharashtra empire?'],
  ['Is there such a thing as golden age of indian culture?'],
  ['Is the vedic period the same as the golden age?']]

how can I convert a 1D list into 2D list?

CodePudding user response:

using list comprehension, you need to iterate through each sublist of lists and do [sentence] on each sentence while iterating over sublist.

result = [[sentence] for sublist in lists for sentence in sublist]

CodePudding user response:

Numpy also has a reshape:

np.array(lists).reshape((-1, 1))

[['Was the indus valley part of the maharashtra empire?']
 ['Is there such a thing as golden age of indian culture?']
 ['Is the vedic period the same as the golden age?']]

CodePudding user response:

If you follow code by @sahasrara62 answer. It will give you list for each character in a lists.

# output for @sahasrara62 code
[['W'], ['a'], ['s'], [' '], ['t'], ['h'], ['e'], [' '], ['i'], ['n'], ['d'], ['u'], ['s'], [' '], ['v'], ['a'], ['l'], ['l'], ['e'], ['y'], [' '], ['p'], ['a'], ['r'], ['t'], [' '], ['o'], ['f'], [' '], ['t'], ['h'], ['e'], [' '], ['m'], ['a'], ['h'], ['a'], ['r'], ['a'], ['s'], ['h'], ['t'], ['r'], ['a'], [' '], ['e'], ['m'], ['p'], ['i'], ['r'], ['e'], ['?'], ['I'], ['s'], [' '], ['t'], ['h'], ['e'], ['r'], ['e'], [' '], ['s'], ['u'], ['c'], ['h'], [' '], ['a'], [' '], ['t'], ['h'], ['i'], ['n'], ['g'], [' '], ['a'], ['s'], [' '], ['g'], ['o'], ['l'], ['d'], ['e'], ['n'], [' '], ['a'], ['g'], ['e'], [' '], ['o'], ['f'], [' '], ['i'], ['n'], ['d'], ['i'], ['a'], ['n'], [' '], ['c'], ['u'], ['l'], ['t'], ['u'], ['r'], ['e'], ['?'], ['I'], ['s'], [' '], ['t'], ['h'], ['e'], [' '], ['v'], ['e'], ['d'], ['i'], ['c'], [' '], ['p'], ['e'], ['r'], ['i'], ['o'], ['d'], [' '], ['t'], ['h'], ['e'], [' '], ['s'], ['a'], ['m'], ['e'], [' '], ['a'], ['s'], [' '], ['t'], ['h'], ['e'], [' '], ['g'], ['o'], ['l'], ['d'], ['e'], ['n'], [' '], ['a'], ['g'], ['e'], ['?']]

You can simply use list comprehension for this.

result = [[sentence] for sentence in lists]
# output
[['Was the indus valley part of the maharashtra empire?'], ['Is there such a thing as golden age of indian culture?'], ['Is the vedic period the same as the golden age?']]
  • Related