0

I have a list:

my_list =`['A', 'B', 'C', '!', '!', 'D', 'E', '!', '!', '!', 'F', 'G', '!']

I would like to print out this list such that whenever there is a gap between the letters 'A' through 'G' (whenever a '!' occurs), only one single '!' is printed out.

So if I were to change this list so then I could print out the elements, the list would look like this:

new_list =`['A', 'B', 'C', '!', 'D', 'E', '!', 'F', 'G', '!']

I am essentially trying to indicate that there is a gap between the letters, not about the size of the gap.

Thanks in advance

Martin
  • 41
  • 5

1 Answers1

2

you can use itertools.groupby:

In [30]: res = [i[0] for i in itertools.groupby(my_list)]

In [31]: res
Out[31]: ['A', 'B', 'C', '!', 'D', 'E', '!', 'F', 'G', '!']
Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41