Skip to content
Advertisement

Sum a list of string based on rule

I have a huge python list as the following example:

JavaScript

I would like to join this information in this formatting:

JavaScript

I have tried this code

JavaScript

But it was not good, since I have something like:

JavaScript

Do you have any idea how can I perform this task?

Advertisement

Answer

You can use itertools.groupby:

JavaScript

It groups the items by whether each item starts with 'name: ';

  1. Items that start with 'name: ' form a group (i.e., ['name: John']).
  2. Next a few items that don’t do so form a group (i.e., ['John has ', '4 yellow ', 'cars.']).
  3. Next items that do so form another group (['name: Angelina']).
  4. … and so on alternatingly.

Then join concatenates the strings in each group.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement