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
x
2
1
array = ['F', '$', '$', '$', 'D', '$', 'C']
2
My end goal is to have this array:
JavaScript
1
2
1
final_array = ['F', ['$', '$', '$'], 'D', ['$'], 'C']
2
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
1
13
13
1
array = ['F', '$', '$', '$', 'D', '$', 'C']
2
3
from itertools import groupby
4
5
result = []
6
for key, group in groupby(array):
7
if key == '$':
8
result.append(list(group))
9
else:
10
result.append(key)
11
12
print(result)
13
You can of course shorten the for-loop to a comprehension:
JavaScript
1
2
1
result = [list(group) if key == '$' else key for key, group in groupby(array)]
2