аватар question@mail.ru · 01.01.1970 03:00

Removing the same elements in a sorted sheet (list)

For example, I have a sheet x = = a, a, a, f, h, k, k] . I need to do so that there would be only one a in this sheet and one k , i.e. Delete extra similar elements, do not touch the rest. Similar elements are always nearby, because The sheet is sorted. How to realize the removal of these extra elements?

аватар answer@mail.ru · 01.01.1970 03:00

You can use the Itertools module:

   from  itertools  import  GroupByx = [ 'a' ,  'a' a ', ' a 'a'  'f' ,  'h' ,  'k' ,  'k' ] new_x = [el  for  el, _  in  in  Groupby (x)]   print  (New_x) # ['a' a 'f', 'h', 'k']      

is better than an option with sett ITERTOOLS.Groupby retains the order in which the elements went in the original sequence. While SET does not guarantee preservation of order.

Latest

Similar