我在不同的日期有车位(X,Y):
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]
]
前三行具有相同的位置,后两行也具有相同的位置。我想将开始日期和结束日期存储在这样的新列表中:
output=[
[21/01/2017,23/01/2017,"carA",2053005.39445,701577.391706],
[24/01/2017,25/01/2017,"carA",2052759.49583,701843.214278]
]
答案 0 :(得分:1)
正如已经提出的那样itertools.groupby
可以使用。但是您的输入必须(正确)排序,因为它只对连续项进行分组:
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]]
另一个提示:input
是一个内置函数,通常不建议使用同名的变量!
请注意,此类列表通常很难在以后处理。您可以将它们存储为collections.namedtuple
,以便为它们提供更多背景信息。