-2

I have car positions (X,Y) at differents dates :

input =[
         [21/01/2017,"carA",2053005.39445,701577.391706],
         [22/01/2017,"carA",2053005.39445,701577.391706],
         [23/01/2017,"carA",2053005.39445,701577.391706],
         [24/01/2017,"carA",2052759.49583,701843.214278],
         [25/01/2017,"carA",2052759.49583,701843.214278]
       ]

The first three lines have the same positions and the last two lines have the same position too. I would like store the start date and the end date in a new list like this:

output=[
        [21/01/2017,23/01/2017,"carA",2053005.39445,701577.391706],
        [24/01/2017,25/01/2017,"carA",2052759.49583,701843.214278]
       ]
MSeifert
  • 145,886
  • 38
  • 333
  • 352
MF78
  • 9
  • Have a look at `itertools.groupby` – Nickil Maveli Feb 23 '17 at 14:23
  • @depperm it's not exactly what i'm trying to do. I try to group the dates by the cars positions (X,Y) and store in other list the start date , the end date and cars positions. So, I have a new element (end date) per output line – MF78 Feb 23 '17 at 14:37
  • Possible duplicate of [Python: remove duplicates from a multi-dimensional array](http://stackoverflow.com/questions/14089453/python-remove-duplicates-from-a-multi-dimensional-array) – miken32 Feb 23 '17 at 21:10

1 Answers1

1

As already proposed itertools.groupby can be used. But your input has to be (correctly) sorted because it only groups consecutive items:

from itertools import groupby
from operator import itemgetter

output = []
for key, group in groupby(input, key=itemgetter(2, 3)):
    group = list(group)
    output.append([group[0][0], group[-1][0]] + group[0][1:])

output
# [['21/01/2017', '23/01/2017', 'carA', 2053005.39445, 701577.391706],
#  ['24/01/2017', '25/01/2017', 'carA', 2052759.49583, 701843.214278]]

Another tip: input is a builtin-function, having a variable with the same name is usually not recommended!


Note that such lists are generally hard to process later. You could instead store them as collections.namedtuple to give them more context.

MSeifert
  • 145,886
  • 38
  • 333
  • 352