0

だから私は次を取る関数を持っています: times= datetime オブジェクトのリスト、start= datetime オブジェクト、およびend= datetime オブジェクト。start と endの間の datetime オブジェクトであるリストを返します

def func(times,start,end):
    return times[start:end],(times.index(start),times.index(end))

startand/orendが実際には datetime オブジェクトのリストにない場合でも動作できるようにする必要があります: times.

したがって、startがリストにない場合は、「より大きい」最初の項目を取得し、リストにないstart場合は同じことを行いますが、end代わりに「より小さい」になります。

実際の開始点と終了点のインデックスを取得することも重要です。

それを行う関数に何を追加しますか?

4

3 に答える 3

1

二分法が使える

import bisect
def func(times, start, end):
    bucket = [start, end]
    out = [x for x in times if bisect.bisect(bucket, x) is 1 or x in bucket]
    return out, (times.index(out[0]), times.index(out[-1]))
于 2013-06-06T05:46:23.897 に答える
0

この質問に対する素朴なアプローチ:

def func(times, start, end):
    s = 0
    e = len(times)-1

    while s < len(times) and times[s]< start: 
        s+=1

    while e >= 0 and times[e] > end: 
        e-=1

    if (e < 0 or s >= len(times) or s > e): 
        return None

    return times[s:e+1], (s,e)
于 2013-06-06T05:50:27.677 に答える
-1

なぜ単純に[dt for dt in times if dt >= start and dt <= end]

于 2013-06-06T05:54:17.207 に答える