collections.defaultdict
ここでbisect
モジュールを使用できます:
範囲は連続しているため、b
最初にリストを次のように変換することをお勧めします。
[10, 40, 60, 90, 100]
これの利点は、bisect
モジュールを使用して、リストのアイテムが収まるインデックスを見つけることができるようになったことです。たとえば、50 は 40 と 60 の間にあるためbisect.bisect_right
、この場合は 2 を返します。いいえ、この 2 をキーとして使用し、リストを値として保存できます。このようにして、 から返されたインデックスに基づいてこれらのアイテムをグループ化できますbisect.bisect_right
。
L_b = 2* len(b)
L_a = len(a)
L_b1 = len(b1)
全体的な複雑さは次のようになります。max ( L_b log L_b , L_a log L_b1 )
>>> import bisect
>>> from collections import defaultdict
>>> b=[(10,40),(40,60),(60,90),(90,100)]
>>> b1 = sorted( set(z for x in b for z in x))
>>> b1
[10, 40, 60, 90, 100]
>>> dic = defaultdict(list)
for x,y in a:
#Now find the index where the value from the list can fit in the
#b1 list, bisect uses binary search so this is an O(log n ) step.
# use this returned index as key and append the list to that key.
ind = bisect.bisect_right(b1,int(x))
dic[ind].append([x,y])
...
>>> dic.values()
[[['10', 'name_1']], [['50', 'name_2'], ['40', 'name_3']], [['80', 'name_N']]]
辞書には特定の順序がないため、並べ替えを使用して並べ替えられた出力を取得します。
>>> [dic[k] for k in sorted(dic)]
[[['10', 'name_1']], [['50', 'name_2'], ['40', 'name_3']], [['80', 'name_N']]]