Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append string to list directly before it in a list of lists and strings

I have a list of lists and strings and would like to append the string elements into the list element directly before it. Below is a sample of the data.

data = [['way','say','may','lay'], 'wake', ['hay','pay','yay'], 'lake', ['tay'], 'shake']

The desire output should be something like this:

out = [['way','say','may','lay','wake'], ['hay','pay','yay','lake'], ['tay', 'shake']]

I have tried converting the list into a dataframe and use groupby and cumsum() however this seems to only partly solve my problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

You could zip together the odd and even parts of data and use list addition of those parts to build your desired output:

out = [odd + [even] for odd, even in zip(data[0::2], data[1::2])]

Output:

[
  ['way', 'say', 'may', 'lay', 'wake'],
  ['hay', 'pay', 'yay', 'lake'],
  ['tay', 'shake']
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading