-2

I have a question about my code because I would like to know how I can remove duplicated elements in my code by keeping the first one each time.

As an example is better than many words :

mylist = [a,a,a,b,c,c,a,d,e,e,e]

I would like to get:

my_new_list = [a,b,c,a,d,e]
my_new_list_2 = [a,3,b,1,c,2,a,1,d,1,e,3]

The process is the following:

As soon as I have a letter or the same following letter, I write this letter one time, then it's the same thing for the next letter etc .. Then I need to remove consecutive duplicates and add the number of duplicates in a new list.

My code is:

mylist = [a,a,a,b,c,c,a,d,e,e,e]
result = list(dict.fromkeys(mylist))
==> [a,b,c,d,e]

It's not the expected result.

ChocoBomb
  • 301
  • 4
  • 15
  • About your code: That will remove _all_ the duplicate elements, not only consecutive ones, as keys in the intermediate (ordered) dict have to be unique. – tobias_k May 13 '19 at 16:35
  • You're right ! It was my first try. But I edited my question because she was not complete and part of my question doesn't find answer in the original post that you mentionned. – ChocoBomb May 13 '19 at 16:36
  • Please explain what part of your question is not handled in the linked duplicate. It appears to me that the duplicate gives you three distinct solutions for your problem. Update your posting with an example that is not handled by the duplicate, please. – Prune May 13 '19 at 16:41

1 Answers1

4

You can use itertools.groupby to group consecutive elements that are equal and keep the key from each group:

from itertools import groupby
mylist = ['a','a','a','b','c','c','a','d','e','e','e']

[k for k,_ in groupby(mylist)]
# ['a', 'b', 'c', 'a', 'd', 'e']
yatu
  • 86,083
  • 12
  • 84
  • 139
  • 1
    Yes it's exactly what I'm watching in another post ! I edited my question because I have another question on this same list – ChocoBomb May 13 '19 at 16:33