Reputation: 654
I have a lists of lists of strings which I would like to convert to a list of strings adding a space between each list item. eg.
original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]
desired_output = ['the cat in the hat', 'fat cat sat on the mat']
I understand that I can do it using this:
desired_output
for each in original_list:
desired_output.append(' '.join(each))
but as I am working with large amounts of data am ideally looking for a more efficient way to do this.
Upvotes: 0
Views: 75
Reputation: 3279
Another pythonic and simple way, in Python 3, could be using map
, says another SO discussion it should be faster, it would go like this:
original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]
# (------where magic happens--------)
desired_list = list(map(' '.join, original_list ))
#print
#output ['the cat in the hat', 'fat cat sat on the mat']
Upvotes: 1
Reputation: 71451
Use str.join
with a full space ' '
:
original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]
final_list = [' '.join(i) for i in original_list]
Output:
['the cat in the hat', 'fat cat sat on the mat']
Upvotes: 4