Skip to content
Advertisement

Python Group Repeated Values in List in a Sublist

I need to append some repeated values from a list into a sublist, let me explain with an example:

I have a variable called array that contains strings of uppercase letters and $ symbols.

JavaScript

My end goal is to have this array:

JavaScript

As in the example, I need to group all $ symbols that are togheter into sublist in the original array, I thought about iterating over the array and finding all symbols near the current $ and then creating a second array, but I think maybe there is something more pythonic I can do, any ideas?

Advertisement

Answer

You can use groupby from itertools

JavaScript

You can of course shorten the for-loop to a comprehension:

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