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.

array = ['F', '$', '$', '$', 'D', '$', 'C']

My end goal is to have this array:

final_array = ['F', ['$', '$', '$'], 'D', ['$'], 'C']

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

array = ['F', '$', '$', '$', 'D', '$', 'C']

from itertools import groupby

result = []
for key, group in groupby(array):
    if key == '$':
        result.append(list(group))
    else:
        result.append(key)

print(result)

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

result = [list(group) if key == '$' else key for key, group in groupby(array)]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement