Home > Blockchain >  How to join two words together in a list with a space in the middle?
How to join two words together in a list with a space in the middle?

Time:11-08

I have a list like this :

['which', 'means', 'which', 'one','which', 'will]

How can I possibly join two words together and form this:

['which means', 'which one', 'which will']

CodePudding user response:

Here's an option using join and zip:

>>> words = ['which', 'means', 'which', 'one', 'which', 'will']
>>> [' '.join(z) for z in zip(words[::2], words[1::2])]
['which means', 'which one', 'which will']

Breaking it down a little to show what the slice operation [::2] does and what zip does:

>>> words[::2], words[1::2]
(['which', 'which', 'which'], ['means', 'one', 'will'])
>>> list(zip(words[::2], words[1::2]))
[('which', 'means'), ('which', 'one'), ('which', 'will')]

A neat thing about this method is that you can change the number of words in the grouping very easily by using another iteration to build the arguments to zip:

>>> list(zip(*(words[i::3] for i in range(3))))
[('which', 'means', 'which'), ('one', 'which', 'will')]
>>> [' '.join(z) for z in zip(*(words[i::3] for i in range(3)))]
['which means which', 'one which will']
  • Related