I've got a list of datetimes from which I want to construct time segments. In other words, turn [t0, t1, ... tn]
into [(t0,t1),(t1,t2),...,(tn-1, tn)]
. I've done it this way:
# start by sorting list of datetimes mdtimes.sort() # construct tuples which represent possible start and end dates # left edges dtg0 = [x for x in mdtimes] dtg0.pop() # right edges dtg1 = [x for x in mdtimes] dtg1.reverse() dtg1.pop() dtg1.sort() dtsegs = zip(dtg0,dtg1)
Questions...
mdtimes
list with list comprehensions? If not how should it be done?The purpose for constructing these tuples is to iterate over them and segment a data set with tn-1
and tn
. Is this a reasonable approach? i.e.
datasegment = [x for x in bigdata if ( (x['datetime'] > tleft) and (x['datetime'] < tright))]
Thanks
Both list
and tuple
are ordered.
dtg0, dtg1 = itertools.tee(mdtimes) next(dtg0) dtsegs = zip(dtg0, dtg1)
Tuple order is as you insert values into the tuple. They're not going to be sorted as I think you're asking. zip
will again, retain the order you inserted the values in.
It's an acceptable method, but I have 2 alternate suggestions: Use the copy module, or use dtg1 = mdtimes[:]
.
Sounds reasonable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With