Stack
Stack

Reputation: 1129

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?

Upvotes: 1

Views: 256

Answers (3)

Stack
Stack

Reputation: 1129

I have made a little change from @rdas answer just in case we have an array with repeated values that we want to keep:

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

result = []
for key, group in groupby(array):
    if key == '$':
        result.append(list(group))
    else:
        for g in list(group):
            result.append(g)
print(result)
# ['F', 'F', ['$', '$', '$'], 'D', ['$'], 'C']

Upvotes: 0

João
João

Reputation: 400

A general approach, that would work in every case (not just '$'):

array = ['F', '$', '$', '$', 'D', '$', 'C']
different_values = []
final_array = []
aux_array = []
old_value = None

for value in array:
    if value not in different_values:
        different_values.append(value)
        final_array.append(value)
        aux_array = []
    else:
        if value == old_value:
            aux_array = list(final_array[-1])
            del final_array[-1]
            aux_array.append(value)
            final_array.append(aux_array)
        else:
            aux_array = [value]
            final_array.append(aux_array)

    old_value = value


print(final_array)

Upvotes: 1

rdas
rdas

Reputation: 21275

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)]

Upvotes: 3

Related Questions