シフト幅を変更できるリスト一括比較
こんな感じの比較。2つ先とか⁺3つ先とかシフト幅を変更できる。
プログラム
def compair(x, y, y_shift, negative=0, na=None): ''' リストを利用した一括の比較 x[i]<=y[i+y_shift]の結果のリストを返す。 Trueのときには1 Falseの時にはnegativeの値が入る。 比較する値がない場合は、naの値が入る。 ''' if len(x) != len(y): raise elif abs(y_shift) >= len(x): raise z = [na] * len(x) if y_shift < 0: for i in range(len(x) + y_shift): # y_shiftは負の数なので、ループ回数は減る。 if x[i - y_shift] is None: z[i - y_shift] = na elif y[i] is None: z[i - y_shift] = na elif x[i - y_shift] <= y[i]: z[i - y_shift] = 1 else: z[i- y_shift] = negative else: for i in range(len(x) - y_shift): if x[i] is None: z[i] = na elif y[i + y_shift] is None: z[i] = na elif x[i] <= y[i + y_shift]: z[i] = 1 else: z[i] = negative return z def compair_offset(x, y, y_shift, y_offset, negative=0, na=None): ''' yの値は、xより、y_offset以上大きい場合。 ''' for i in range(len(y)): y[i] = y[i] - y_offset z = compair(x, y, y_shift, negative, na) return z if __name__ == "__main__": x = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9] y = [2, 7, 1, 8, 2, 8, 1, 8, 2, 8, 4, 6] print(compair(x, y, 0)) print(compair(x, y, 1)) print(compair(x, y, 2)) print(compair(x, y, 10)) print(compair(x, y, 11)) print(compair(x, y, -1)) print(compair(x, y, -2)) print(compair(x, y, -10)) print(compair(x, y, -11)) print(compair(x, y, 3, na=0)) print(compair(x, y, -3, negative=0)) print(compair_offset(x, y, y_shift=0, y_offset=2, negative=0)) print(compair_offset(x, y, y_shift=2, y_offset=2, negative=0))
結果
[0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0] [1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, None] [0, 1, 0, 1, 0, 0, 1, 1, 0, 1, None, None] [1, 1, None, None, None, None, None, None, None, None, None, None] [1, None, None, None, None, None, None, None, None, None, None, None] [None, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0] [None, None, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0] [None, None, None, None, None, None, None, None, None, None, 0, 0] [None, None, None, None, None, None, None, None, None, None, None, 0] [1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0] [None, None, None, 1, 1, 0, 1, 0, 1, 0, 1, 0] [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0] [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, None, None]