0

How can I write a function that deletes any repeated strings. In the list dates the strings '2017-11-01 00:00:00','2018-12-01 00:00:00' has been repeated twice or more. I want to get it to the point where it is of the Expected Output and where there is only 1 case for each string.

dates = ['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00:00', '2017-11-01 00:00:00', '2017-11-01 00:00:00', '2017-12-01 00:00:00', '2018-01-01 00:00:00', '2018-02-01 00:00:00', '2018-03-01 00:00:00', '2018-04-01 00:00:00', '2018-05-01 00:00:00', '2018-06-01 00:00:00', '2018-07-01 00:00:00', '2018-08-01 00:00:00', '2018-09-01 00:00:00', '2018-10-01 00:00:00', '2018-11-01 00:00:00', '2018-12-01 00:00:00', '2018-12-01 00:00:00', '2019-01-01 00:00:00']

Expected Output:

['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00:00', '2017-12-01 00:00:00', '2018-01-01 00:00:00', '2018-02-01 00:00:00', '2018-03-01 00:00:00', '2018-04-01 00:00:00', '2018-05-01 00:00:00', '2018-06-01 00:00:00', '2018-07-01 00:00:00', '2018-08-01 00:00:00', '2018-09-01 00:00:00', '2018-10-01 00:00:00', '2018-11-01 00:00:00', '2018-12-01 00:00:00', '2019-01-01 00:00:00']
georgehere
  • 610
  • 3
  • 12

1 Answers1

0

Assuming you want to filter out consecutives repeats, you can use a list comprehension:

[dates[0]]+[dates[i] for i in range(1, len(dates)) if dates[i-1]!=dates[i]]

or itertools.groupby:

from itertools import groupby
[list(g)[0] for i,g in groupby(dates)]

output:

['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00:00',
 '2017-12-01 00:00:00', '2018-01-01 00:00:00', '2018-02-01 00:00:00',
 '2018-03-01 00:00:00', '2018-04-01 00:00:00', '2018-05-01 00:00:00',
 '2018-06-01 00:00:00', '2018-07-01 00:00:00', '2018-08-01 00:00:00',
 '2018-09-01 00:00:00', '2018-10-01 00:00:00', '2018-11-01 00:00:00',
 '2018-12-01 00:00:00', '2019-01-01 00:00:00']
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Thank you it works, is there a way I could do it with `integers` instead of `strings`. I tried `[int(g)[0] for i,g in groupby(month_changes)]` with a list numbers like `[2,2,3,4,5,6,7]`, it gives me this error msg `TypeError: int() argument must be a string, a bytes-like object or a number, not 'itertools._grouper'` – georgehere Sep 10 '21 at 19:04
  • It should work with integers, just use the exact same code. The`list` is here to expand the group generator. – mozway Sep 11 '21 at 02:23