bisect を使った範囲検索(例: 20〜40 の値をまとめて取り出す)
bisect は「挿入位置」を返すので、範囲検索にも応用できます。
例えば「20〜40 の値をまとめて取り出す」場合は、bisect_left と bisect_right を組み合わせます。
基本の考え方
bisect_left(a, lower)→ 下限値lowerを挿入すべき位置(含む)bisect_right(a, upper)→ 上限値upperを挿入すべき位置(含まない)- その範囲をスライスすれば、指定範囲の値をまとめて取得できる。
具体例
import bisect
data = [10, 15, 20, 25, 30, 35, 40, 45, 50] # ソート済みリスト
lower, upper = 20, 40
# 範囲の開始位置と終了位置を取得
start = bisect.bisect_left(data, lower)
end = bisect.bisect_right(data, upper)
# 範囲の値をまとめて取り出す
subset = data[start:end]
print(subset) # [20, 25, 30, 35, 40]
Python応用例
1. 年齢データから特定範囲を抽出
ages = [18, 21, 25, 29, 32, 35, 40, 45, 50]
young_adults = ages[bisect.bisect_left(ages, 20):bisect.bisect_right(ages, 30)]
print(young_adults) # [21, 25, 29]
Python2. スコア分布から合格者(60〜80点)を抽出
scores = [45, 55, 60, 65, 70, 75, 80, 85, 90]
passed = scores[bisect.bisect_left(scores, 60):bisect.bisect_right(scores, 80)]
print(passed) # [60, 65, 70, 75, 80]
Pythonまとめ
bisect_leftとbisect_rightを組み合わせると、範囲検索が簡単にできる。- ソート済みリストなら、大規模データでも高速に抽出可能。
- 応用例: 年齢層の抽出、スコア分布の分析、ログの時間範囲検索など。

