1

I have two lists in a list:

t = [['this','is','a','sentence'],['Hello','I','am','Daniel']]

I want to combine them in order to get two sentences:

'this is a sentence. Hello I am Daniel.'

I quickly came up with the following solution:

text = ''
for sent in t:
  text = text + ' '.join(sent) + '. ' 

But maybe there is more readable(better styled) solution for this task?

2 Answers2

3

You can shorten it to a single list comprehension, with another "." at the end:

text = '. '.join(' '.join(sent) for sent in t) + '.'
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • @jizhihaoSAMA thanks! always important to make sure output is an exact match :D – Adam.Er8 Apr 13 '20 at 13:54
  • 1
    Note that actually building the intermediate list: `'. '.join([' '.join(sent) for sent in t])` is a bit faster (10 to 20%). See [this answer](https://stackoverflow.com/a/9061024/550094) that explains why. – Thierry Lathuille Apr 13 '20 at 13:57
1

You could also use list comprehensions:

In [584]: ''.join([' '+ ' '.join(sent) + '. ' for sent in t])                                                                                                                                               
Out[584]: ' this is a sentence.  Hello I am Daniel. '
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58